-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
isbn.go
89 lines (73 loc) · 1.52 KB
/
isbn.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
package checkdigit
type (
isbn10 struct{}
isbn13 struct{}
)
// Verify implements checkdigit.Verifier interface.
func (i10 isbn10) Verify(code string) bool {
if len(code) != 10 {
return false
}
sum, multiply := 0, 10
for _, n := range code {
var digit int
switch {
case n == 'X':
digit = 10
case isNotNumber(n):
return false
default:
digit = int(n - '0')
}
sum += multiply * digit
multiply--
}
return sum%11 == 0
}
// Generate implements checkdigit.Generator interface.
// This will return a "10" instead of an "X", since the interface expects an int.
func (i10 *isbn10) Generate(seed string) (int, error) {
if len(seed) != 9 {
return 0, ErrInvalidArgument
}
sum, multiply := 0, 10
for _, n := range seed {
if isNotNumber(n) {
return 0, ErrInvalidArgument
}
sum += multiply * int(n-'0')
multiply--
}
return 11 - sum%11, nil
}
// Verify implements checkdigit.Verifier interface.
func (i13 isbn13) Verify(code string) bool {
if len(code) != 13 {
return false
}
i, err := i13.Generate(code[:len(code)-1])
return err == nil && i == int(code[len(code)-1]-'0')
}
// Generate implements checkdigit.Generator interface.
func (i13 *isbn13) Generate(seed string) (int, error) {
if len(seed) != 12 {
return 0, ErrInvalidArgument
}
sum, weight := 0, 1
for _, n := range seed {
if isNotNumber(n) {
return 0, ErrInvalidArgument
}
sum += int(n-'0') * weight
if weight == 1 {
weight = 3
} else {
weight = 1
}
}
d := 10 - sum%10
if d == 10 {
d = 0
}
return d, nil
}