@@ -34,14 +34,20 @@ func GenerateBrazilianVoteRegistration(formatted bool) (*BrazilianVoteRegistrati
3434 stateCodeStr := fmt .Sprintf ("%02d" , stateCode )
3535
3636 // Calculate the first check digit
37- checkDigit1 := calculateCheckDigit1 (sequenceNumberStr )
37+ checkDigit1 , err := calculateCheckDigit1 (sequenceNumberStr )
38+ if err != nil {
39+ return nil , err
40+ }
3841
3942 // Calculate the second check digit
40- checkDigit2 := calculateCheckDigit2 (stateCodeStr , checkDigit1 , stateCode )
43+ checkDigit2 , err := calculateCheckDigit2 (stateCodeStr , checkDigit1 , stateCode )
44+ if err != nil {
45+ return nil , err
46+ }
4147
4248 // Combine everything to form the complete number
4349 number := sequenceNumberStr + stateCodeStr + checkDigit1 + checkDigit2
44- if number == "" {
50+ if number == "" || len ( number ) != 12 {
4551 return nil , ErrInvalidVoteRegistration
4652 }
4753
@@ -70,11 +76,14 @@ func randomInt3Digits() string {
7076
7177// calculateCheckDigit1 calculates the first check digit.
7278// It depends on the sequence number.
73- func calculateCheckDigit1 (sequenceNumber string ) string {
79+ func calculateCheckDigit1 (sequenceNumber string ) ( string , error ) {
7480 sum := 0
7581 weights := []int {2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }
7682 for i := 0 ; i < len (sequenceNumber ); i ++ {
77- digit , _ := strconv .Atoi (string (sequenceNumber [i ]))
83+ digit , err := strconv .Atoi (string (sequenceNumber [i ]))
84+ if err != nil {
85+ return "" , ErrInvalidCheckDigit1
86+ }
7887 sum += digit * weights [i ]
7988 }
8089
@@ -83,19 +92,25 @@ func calculateCheckDigit1(sequenceNumber string) string {
8392 checkDigit1 = 0
8493 }
8594
86- return strconv .Itoa (checkDigit1 )
95+ return strconv .Itoa (checkDigit1 ), nil
8796}
8897
8998// calculateCheckDigit2 calculates the second check digit.
9099// It depends on the state code and the first check digit.
91- func calculateCheckDigit2 (stateCode , checkDigit1 string , stateCodeInt int ) string {
100+ func calculateCheckDigit2 (stateCode , checkDigit1 string , stateCodeInt int ) ( string , error ) {
92101 sum := 0
93102 weights := []int {7 , 8 }
94103 for i := 0 ; i < len (stateCode ); i ++ {
95- digit , _ := strconv .Atoi (string (stateCode [i ]))
104+ digit , err := strconv .Atoi (string (stateCode [i ]))
105+ if err != nil {
106+ return "" , ErrInvalidCheckDigit2
107+ }
96108 sum += digit * weights [i ]
97109 }
98- checkDigit1Int , _ := strconv .Atoi (checkDigit1 )
110+ checkDigit1Int , err := strconv .Atoi (checkDigit1 )
111+ if err != nil {
112+ return "" , ErrInvalidCheckDigit2
113+ }
99114 sum += checkDigit1Int * 9
100115
101116 checkDigit2 := sum % 11
@@ -108,5 +123,5 @@ func calculateCheckDigit2(stateCode, checkDigit1 string, stateCodeInt int) strin
108123 checkDigit2 = 1
109124 }
110125
111- return strconv .Itoa (checkDigit2 )
126+ return strconv .Itoa (checkDigit2 ), nil
112127}
0 commit comments