-
Notifications
You must be signed in to change notification settings - Fork 0
/
zbase32.go
72 lines (56 loc) · 1.35 KB
/
zbase32.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
package zbase32
import (
"errors"
)
type encoding struct {
encodeMap string
decodeMap [256]byte
}
func newEncoding(encodeMap string) *encoding {
e := new(encoding)
e.encodeMap = encodeMap
for i := 0; i < len(e.decodeMap); i++ {
e.decodeMap[i] = 0xFF
}
for i := 0; i < len(encodeMap); i++ {
e.decodeMap[encodeMap[i]] = byte(i)
}
return e
}
var zBase32Encoding = newEncoding("ybndrfg8ejkmcpqxot1uwisza345h769")
var InsufficientInputError = errors.New("too few bytes supplied for z-base-32 encoding")
func Encode(src []byte, bits int) (string, error) {
if bits > len(src) * 8 {
return "", InsufficientInputError
}
buf := make([]byte, (bits+4)/5)
dst := buf
for i := 0; i < bits; i += 5 {
b0 := src[0]
b1 := byte(0)
if len(src) > 1 {
b1 = src[1]
}
char := byte(0)
offset := uint(i % 8)
if offset < 4 {
char = b0 & (31 << (3 - offset)) >> (3 - offset)
} else {
char = b0 & (31 >> (offset - 3)) << (offset - 3)
char |= b1 & (255 << (11 - offset)) >> (11 - offset)
}
// If src is longer than necessary, mask trailing bits to zero
if i + 5 > bits {
char &= 255 << uint((i + 5) - bits)
}
dst[0] = zBase32Encoding.encodeMap[char]
dst = dst[1:]
if offset > 2 {
src = src[1:]
}
}
return string(buf), nil
}
func EncodeAll(src []byte) (string, error) {
return Encode(src, len(src)*8)
}