-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
101 lines (86 loc) · 2.07 KB
/
encoding.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
100
101
package radix
import (
"errors"
"fmt"
)
// Encode encodes input to string with alphabet.
func Encode(input []int, alphabet string) (output string, err error) {
runes := []rune(alphabet)
if len(runes) < 2 {
return "", errors.New("len(alphabet) less than 2")
}
if len(input) == 0 {
return "", nil
}
for i, v := range input {
if v >= len(runes) {
return "", fmt.Errorf("input[%v]: %v must be less than len(alphabet): %v", i, v, len(runes))
}
output += string(runes[v])
}
return
}
// Decode decodes input string by alphabet.
func Decode(input string, alphabet string) (output []int, err error) {
runes := []rune(alphabet)
if len(runes) < 2 {
return nil, errors.New("len(alphabet) less than 2")
}
if input == "" {
return nil, nil
}
runesMap := make(map[rune]int)
for i, r := range runes {
runesMap[r] = i
}
for i, r := range input {
if v, ok := runesMap[r]; ok {
output = append(output, v)
} else {
return nil, fmt.Errorf("rune %q at %v not contained in alphabet", r, i)
}
}
return
}
// EncodeBytes encodes bytes input to string with alphabet.
func EncodeBytes(input []byte, alphabet string) (output string, err error) {
runes := []rune(alphabet)
if len(runes) < 2 {
return "", errors.New("len(alphabet) less than 2")
}
if len(input) == 0 {
return "", nil
}
for i, v := range input {
if int(v) >= len(runes) {
return "", fmt.Errorf("input[%v]: %v must be less than len(alphabet): %v", i, v, len(runes))
}
output += string(runes[v])
}
return
}
// DecodeBytes decodes input string by alphabet to bytes output.
func DecodeBytes(input string, alphabet string) (output []byte, err error) {
runes := []rune(alphabet)
if len(runes) < 2 {
return nil, errors.New("len(alphabet) less than 2")
}
if input == "" {
return nil, nil
}
runesMap := make(map[rune]byte)
for i, r := range runes {
if i > 255 {
break
}
runesMap[r] = byte(i)
}
for i, r := range input {
if v, ok := runesMap[r]; ok {
output = append(output, v)
} else {
return nil, fmt.Errorf("rune %q at %v not contained in alphabet", r, i)
}
}
return
}