-
Notifications
You must be signed in to change notification settings - Fork 2
/
cnpj.go
143 lines (119 loc) · 2.33 KB
/
cnpj.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package br
import (
"errors"
"github.com/phenpessoa/gutils/unsafex"
)
var (
// ErrInvalidCNPJ is an error returned when an invalid CNPJ is encountered.
ErrInvalidCNPJ = errors.New("br: invalid cnpj passed")
cnpjFirstTable = []int{5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
cnpjSecondTable = []int{6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2}
)
// NewCNPJ creates a new CNPJ instance from a string representation.
//
// It verifies the CNPJ's validity using checksum digits.
func NewCNPJ(s string) (CNPJ, error) {
cnpj := CNPJ(s)
if !cnpj.IsValid() {
return "", ErrInvalidCNPJ
}
return cnpj, nil
}
// CNPJ represents a Brazilian CNPJ.
type CNPJ string
// IsValid checks whether the provided CNPJ is valid based on its checksum
// digits.
func (cnpj CNPJ) IsValid() bool {
l := len(cnpj)
if l != 14 && l != 18 {
return false
}
dByte, ok := iterCNPJTable(cnpj, cnpjFirstTable)
if !ok {
return false
}
if cnpj[l-2] != dByte {
return false
}
dByte, ok = iterCNPJTable(cnpj, cnpjSecondTable)
if !ok {
return false
}
if cnpj[l-1] != dByte {
return false
}
return true
}
func iterCNPJTable(cnpj CNPJ, table []int) (byte, bool) {
var sum, pad, rest, d int
for i, d := range table {
cur := cnpj[i+pad]
switch cur {
case '.':
if i != 2 && i != 5 {
return 0, false
}
pad++
cur = cnpj[i+pad]
case '/':
if i != 8 {
return 0, false
}
pad++
cur = cnpj[i+pad]
case '-':
if i != 12 {
return 0, false
}
pad++
cur = cnpj[i+pad]
}
if cur < '0' || cur > '9' {
return 0, false
}
sum += d * int(cur-'0')
}
rest = sum % 11
if rest >= 2 {
d = 11 - rest
}
return byte(d) + '0', true
}
// String returns the formatted CNPJ string with punctuation as
// XX.XXX.XXX/XXXX-XX.
func (cnpj CNPJ) String() string {
if !cnpj.IsValid() {
return ""
}
if len(cnpj) == 18 {
return string(cnpj)
}
out := make([]byte, 18)
for i := range cnpj {
switch {
case i < 2:
out[i] = cnpj[i]
case i == 2:
out[i] = '.'
out[i+1] = cnpj[i]
case i < 5:
out[i+1] = cnpj[i]
case i == 5:
out[i+1] = '.'
out[i+2] = cnpj[i]
case i < 8:
out[i+2] = cnpj[i]
case i == 8:
out[i+2] = '/'
out[i+3] = cnpj[i]
case i < 12:
out[i+3] = cnpj[i]
case i == 12:
out[i+3] = '-'
out[i+4] = cnpj[i]
default:
out[i+4] = cnpj[i]
}
}
return unsafex.String(out)
}