- Notifications
You must be signed in to change notification settings - Fork28
/
Copy pathrg.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
funcIsRG(docstring,ufFederativeUnit) (isValidbool,errerror) {
ifuf!=SP&&uf!=RJ {
returnfalse,errNotImplementedUF
}
if!rgRegexp[uf].MatchString(doc) {
returnfalse,nil
}
checkDigit:=getRGCheckDigit(doc)
calculatedCheckDigit:=calculateRGCheckDigit(doc)
returncalculatedCheckDigit==checkDigit,nil
}
funccalculateRGCheckDigit(docstring)int {
doc=cleanNonRGDigits(doc)
digitsSum:=0
fori,digit:=rangedoc[:len(doc)-1] {
a:=toInt(digit)* (i+2)
digitsSum+=a
}
return11- (digitsSum%11)
}
funcgetRGCheckDigit(docstring)int {
switchlastDigit:=rune(doc[len(doc)-1]);lastDigit {
case'X','x':
return10
case'0':
return11
default:
returntoInt(lastDigit)
}
}
// cleanNonDigits removes every rune that is not a valid RG digit.
funccleanNonRGDigits(docstring)string {
buf:=bytes.NewBufferString("")
for_,r:=rangedoc {
ifisRGValidDigit(r) {
buf.WriteRune(r)
}
}
returnbuf.String()
}
funcisRGValidDigit(rrune)bool {
returnunicode.IsDigit(r)||r=='X'||r=='x'
}