-
Notifications
You must be signed in to change notification settings - Fork 2
/
cpf.go
131 lines (108 loc) · 2.14 KB
/
cpf.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
package br
import (
"database/sql/driver"
"errors"
"github.com/phenpessoa/gutils/unsafex"
)
var (
// ErrInvalidCPF is an error returned when an invalid CPF is encountered.
ErrInvalidCPF = errors.New("br: invalid cpf passed")
cpfFirstTable = []int{10, 9, 8, 7, 6, 5, 4, 3, 2}
cpfSecondTable = []int{11, 10, 9, 8, 7, 6, 5, 4, 3, 2}
)
// NewCPF creates a new CPF instance from a string representation.
//
// It verifies the CPF's validity using checksum digits.
func NewCPF(s string) (CPF, error) {
cpf := CPF(s)
if !cpf.IsValid() {
return "", ErrInvalidCPF
}
return cpf, nil
}
// CPF represents a Brazilian CPF.
type CPF string
// IsValid checks whether the provided CPF is valid based on its checksum
// digits.
func (cpf CPF) IsValid() bool {
l := len(cpf)
if l != 11 && l != 14 {
return false
}
dByte, ok := iterCPFTable(cpf, cpfFirstTable)
if !ok {
return false
}
if cpf[l-2] != dByte {
return false
}
dByte, ok = iterCPFTable(cpf, cpfSecondTable)
if !ok {
return false
}
return cpf[l-1] == dByte
}
func iterCPFTable(cpf CPF, table []int) (byte, bool) {
var sum, pad, rest, d int
for i, d := range table {
cur := cpf[i+pad]
switch cur {
case '.':
if i != 3 && i != 6 {
return 0, false
}
pad++
cur = cpf[i+pad]
case '-':
if i != 9 {
return 0, false
}
pad++
cur = cpf[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 CPF string with punctuation as XXX.XXX.XXX-XX.
func (cpf CPF) String() string {
if !cpf.IsValid() {
return ""
}
if len(cpf) == 14 {
return string(cpf)
}
out := make([]byte, 14)
for i := range cpf {
switch {
case i < 3:
out[i] = cpf[i]
case i == 3:
out[i] = '.'
out[i+1] = cpf[i]
case i < 6:
out[i+1] = cpf[i]
case i == 6:
out[i+1] = '.'
out[i+2] = cpf[i]
case i < 9:
out[i+2] = cpf[i]
case i == 9:
out[i+2] = '-'
out[i+3] = cpf[i]
default:
out[i+3] = cpf[i]
}
}
return unsafex.String(out)
}
func (c CPF) Value() (driver.Value, error) {
return c.String(), nil
}