-
Notifications
You must be signed in to change notification settings - Fork 28
/
rg.go
76 lines (62 loc) · 1.57 KB
/
rg.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
package brdoc
import (
"bytes"
"errors"
"regexp"
"unicode"
)
var (
rgRegexp = map[FederativeUnit]*regexp.Regexp{
SP: regexp.MustCompile(`^\d{2}\.?\d{3}\.?\d{3}-?[0-9xX]$`),
RJ: regexp.MustCompile(`^\d{2}\.?\d{3}\.?\d{3}-?[0-9xX]$`),
}
errNotImplementedUF = errors.New("federative unit not implemented")
)
// IsRG verifies if `doc` is a valid RG.
// `uf` represents the Federative Unit the RG belongs to.
// Currently, the only implemented UFs are the following (the remaining will return an error):
// - SP
// - RJ
func IsRG(doc string, uf FederativeUnit) (isValid bool, err error) {
if uf != SP && uf != RJ {
return false, errNotImplementedUF
}
if !rgRegexp[uf].MatchString(doc) {
return false, nil
}
checkDigit := getRGCheckDigit(doc)
calculatedCheckDigit := calculateRGCheckDigit(doc)
return calculatedCheckDigit == checkDigit, nil
}
func calculateRGCheckDigit(doc string) int {
doc = cleanNonRGDigits(doc)
digitsSum := 0
for i, digit := range doc[:len(doc)-1] {
a := toInt(digit) * (i + 2)
digitsSum += a
}
return 11 - (digitsSum % 11)
}
func getRGCheckDigit(doc string) int {
switch lastDigit := rune(doc[len(doc)-1]); lastDigit {
case 'X', 'x':
return 10
case '0':
return 11
default:
return toInt(lastDigit)
}
}
// cleanNonDigits removes every rune that is not a valid RG digit.
func cleanNonRGDigits(doc string) string {
buf := bytes.NewBufferString("")
for _, r := range doc {
if isRGValidDigit(r) {
buf.WriteRune(r)
}
}
return buf.String()
}
func isRGValidDigit(r rune) bool {
return unicode.IsDigit(r) || r == 'X' || r == 'x'
}