-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase62.go
49 lines (42 loc) · 976 Bytes
/
base62.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
package main
import (
"errors"
"fmt"
"strings"
)
// Characters defines the character set for base 62 encoding
const Characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const base = len(Characters)
var digits = make(map[rune]int)
func init() {
for i, char := range Characters {
digits[char] = i
}
}
// Encode a non-negative integer into a base 62 symbol string
func Encode(id int) (string, error) {
if id < 0 {
return "", errors.New("argument to Encode must be non-negative")
}
var sb strings.Builder
for id > 0 {
rem := id % base
sb.WriteByte(Characters[rem])
id = id / base
}
return sb.String(), nil
}
// Decode a base 62 encoded string
func Decode(str string) (int, error) {
id := 0
coeff := 1
for _, char := range str {
digit := digits[char]
if char != '0' && digit == 0 {
return 0, fmt.Errorf(`argument "%s" contains illegal character(s)`, str)
}
id += coeff * digit
coeff *= base
}
return id, nil
}