-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathluhn.go
55 lines (49 loc) · 995 Bytes
/
luhn.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
// Information about the algorithm is available on Wikipedia
//
// https://en.wikipedia.org/wiki/Luhn_algorithm
//
package luhn
import "fmt"
var m = [10]uint{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}
var zero = uint('0')
// Digit returns luhn digit for given numeric string
func Digit(cc string) (uint, error) {
var (
i int = len(cc) - 1
x uint
d uint
)
loop:
if i < 0 {
x = (10 - (x - (x/10)*10))
if x == 10 {
return 0, nil
}
return x, nil
}
d = uint(cc[i]) - zero
if d > 9 {
return 1, fmt.Errorf("string must contain only digits")
}
switch i & 1 {
case 1:
x += d
default:
x += m[d]
}
i--
goto loop
}
// Validate returns true if numeric string is signed with valid luhn digit
func Validate(cc string) (ok bool) {
digit, err := Digit(cc)
return err == nil && digit == 0
}
// Generate signs string with luhn digit
func Generate(cc string) (string, error) {
digit, err := Digit(cc)
if err != nil {
return cc, err
}
return cc + string(rune(digit+zero)), nil
}