mirror of
https://github.com/octoleo/syncthing.git
synced 2025-01-22 22:58:25 +00:00
Luhn docs
This commit is contained in:
parent
193cea95ce
commit
cfb33321b0
10
luhn/luhn.go
10
luhn/luhn.go
@ -1,14 +1,18 @@
|
|||||||
|
// Package luhn generates and validates Luhn mod N check digits.
|
||||||
package luhn
|
package luhn
|
||||||
|
|
||||||
import "strings"
|
import "strings"
|
||||||
|
|
||||||
|
// An alphabet is a string of N characters, representing the digits of a given
|
||||||
|
// base N.
|
||||||
type Alphabet string
|
type Alphabet string
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Base32 Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="
|
Base32 Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||||
Base32Trimmed 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 {
|
func (a Alphabet) Generate(s string) rune {
|
||||||
factor := 1
|
factor := 1
|
||||||
sum := 0
|
sum := 0
|
||||||
@ -30,6 +34,8 @@ func (a Alphabet) Generate(s string) rune {
|
|||||||
return rune(a[checkCodepoint])
|
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 {
|
func (a Alphabet) Validate(s string) bool {
|
||||||
t := s[:len(s)-1]
|
t := s[:len(s)-1]
|
||||||
c := a.Generate(t)
|
c := a.Generate(t)
|
||||||
|
@ -7,11 +7,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestGenerate(t *testing.T) {
|
func TestGenerate(t *testing.T) {
|
||||||
|
// Base 6 Luhn
|
||||||
a := luhn.Alphabet("abcdef")
|
a := luhn.Alphabet("abcdef")
|
||||||
c := a.Generate("abcdef")
|
c := a.Generate("abcdef")
|
||||||
if c != 'e' {
|
if c != 'e' {
|
||||||
t.Errorf("Incorrect check digit %c != e", c)
|
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) {
|
func TestValidate(t *testing.T) {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user