-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathluhn.go
99 lines (75 loc) · 2.6 KB
/
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
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
// Package luhn implements a simple manager for Luhn Mod N checksum calculation and validation.
package luhn
import (
"strconv"
)
// Carries the chosen configuration and exposes the API.
type Manager struct {
base int // Base (or Modulus) chosen. Common bases are 10, 16 and 36.
}
// Create a new checksum manager to create and validate coded strings.
// The base must be in the allowed range.
// It returns an instance that can be used to perform checksum calculation and validation.
func New(base int) (Manager, error) {
err := isAllowed(base)
if err != nil {
return Manager{}, err
}
return Manager{base: base}, nil
}
// Check that a code string is valid.
// The checksum must be the last character.
func (m Manager) IsValid(code string) bool {
// Separate original checksum and payload.
originalChecksum := string(code[len(code)-1])
code = code[:len(code)-1]
c, err := m.GetChecksum(code)
if err != nil {
return false
}
return c == originalChecksum
}
// Generate the checksum for a given input string.
// The input must *not* have a checksum suffix.
func (m Manager) GetChecksum(input string) (string, error) {
var sum uint64
if len(input) < 1 {
// Empty string have no checksum.
return "", ErrInvalidValue
}
base := uint64(m.base)
for i := int(0); i < len(input); i++ {
// From the rightmost digit.
// ParseUint will accept both lowercase and uppercase characters.
// All characters are lowercase as used in strconv package.
v, err := strconv.ParseUint(string(input[i]), m.base, strconv.IntSize)
if err != nil {
return "", err
}
// Double the value of every second digit from the left.
// For i = 1,3,5,etc.
v *= (1 + uint64(i)%2)
// Add digits together when above base. Only relevant when v >= base.
// NOTE: Since we double each digit, the maximum possible value of v at this point is 2*(base-1).
v = v/base + v%base
sum += v
}
sum = (base - (sum % base)) % base // The smallest number (possibly zero) that must be added to sum to make it a multiple of the base.
// FormatUint returns lowercase a-z characters. Enforcing uppercase (as more commonly used for codes).
// TODO: Add an option in constructor.
return strconv.FormatUint(sum, m.base), nil
}
// Internal helper to validate possible bases.
// The Luhn mod N algorithm only works when N is divisible by 2.
func isAllowed(base int) error {
if base < 2 || base > 36 {
// Relying on the [strconv.FormatUint] function specs.
// Range is 2 <= base <= 36.
return ErrInvalidBase
}
if base%2 != 0 {
// Base must be divisible by 2 for the Luhn algorithm to be effective.
return ErrInvalidBase
}
return nil
}