diff --git a/luhn/luhn.go b/luhn/luhn.go index 2158104a7..ab87e42bf 100644 --- a/luhn/luhn.go +++ b/luhn/luhn.go @@ -1,14 +1,18 @@ +// Package luhn generates and validates Luhn mod N check digits. package luhn import "strings" +// An alphabet is a string of N characters, representing the digits of a given +// base N. type Alphabet string var ( - Base32 Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=" - Base32Trimmed Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + Base32 Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" ) +// Generate returns a check digit for the string s, which should be composed +// of characters from the Alphabet a. func (a Alphabet) Generate(s string) rune { factor := 1 sum := 0 @@ -30,6 +34,8 @@ func (a Alphabet) Generate(s string) rune { return rune(a[checkCodepoint]) } +// Validate returns true if the last character of the string s is correct, for +// a string s composed of characters in the alphabet a. func (a Alphabet) Validate(s string) bool { t := s[:len(s)-1] c := a.Generate(t) diff --git a/luhn/luhn_test.go b/luhn/luhn_test.go index 5702fd7e9..dcf8513bf 100644 --- a/luhn/luhn_test.go +++ b/luhn/luhn_test.go @@ -7,11 +7,19 @@ import ( ) func TestGenerate(t *testing.T) { + // Base 6 Luhn a := luhn.Alphabet("abcdef") c := a.Generate("abcdef") if c != 'e' { t.Errorf("Incorrect check digit %c != e", c) } + + // Base 10 Luhn + a = luhn.Alphabet("0123456789") + c = a.Generate("7992739871") + if c != '3' { + t.Errorf("Incorrect check digit %c != 3", c) + } } func TestValidate(t *testing.T) {