Luhn docs

This commit is contained in:
Jakob Borg 2014-07-04 15:56:33 +02:00
parent 193cea95ce
commit cfb33321b0
2 changed files with 16 additions and 2 deletions

View File

@ -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)

View File

@ -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) {