-
Notifications
You must be signed in to change notification settings - Fork 5
/
integer.go
65 lines (58 loc) · 1.72 KB
/
integer.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
package base62
// FormatInt encodes an integer num to base62 using the encoding enc.
func (enc *Encoding) FormatInt(num int64) []byte {
dst := make([]byte, 0)
return enc.AppendUint(dst, uint64(num))
}
// FormatUint encodes an unsigned integer num to base62 using the encoding enc.
func (enc *Encoding) FormatUint(num uint64) []byte {
dst := make([]byte, 0)
return enc.AppendUint(dst, num)
}
// AppendInt appends the base62 representation of the integer num,
// as generated by FormatInt, to dst and returns the extended buffer.
func (enc *Encoding) AppendInt(dst []byte, num int64) []byte {
return enc.AppendUint(dst, uint64(num))
}
// AppendUint appends the base62 representation of the unsigned integer num,
// as generated by FormatUint, to dst and returns the extended buffer.
func (enc *Encoding) AppendUint(dst []byte, num uint64) []byte {
if num == 0 {
dst = append(dst, enc.encode[0])
return dst
}
var buf [11]byte
var i = 11
for num > 0 {
r := num % base
num /= base
i--
buf[i] = enc.encode[r]
}
dst = append(dst, buf[i:]...)
return dst
}
// ParseInt returns an integer from its base62 representation.
//
// If src contains invalid base62 data, it returns 0 and CorruptInputError.
func (enc *Encoding) ParseInt(src []byte) (int64, error) {
num, err := enc.ParseUint(src)
if err != nil {
return 0, err
}
return int64(num), nil
}
// ParseUint returns an unsigned integer from its base62 representation.
//
// If src contains invalid base62 data, it returns 0 and CorruptInputError.
func (enc *Encoding) ParseUint(src []byte) (uint64, error) {
var num uint64
for i, c := range src {
x := enc.decodeMap[c]
if x == 0xFF {
return 0, CorruptInputError(i)
}
num = num*base + uint64(x)
}
return num, nil
}