-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase62.go
More file actions
51 lines (43 loc) · 961 Bytes
/
base62.go
File metadata and controls
51 lines (43 loc) · 961 Bytes
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
/*
* Copyright (c) 2019-2026 Mikhail Knyazhev <markus621@yandex.com>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/
package base62
import (
"bytes"
"go.osspkg.com/algorithms/sorts"
)
const size = 62
type Base62 struct {
enc []byte
dec map[byte]uint64
}
func New(alphabet string) *Base62 {
if len(alphabet) != size {
panic("encoding alphabet is not 62-bytes long")
}
v := &Base62{
enc: []byte(alphabet),
dec: make(map[byte]uint64, size),
}
for i, b := range v.enc {
v.dec[b] = uint64(i)
}
return v
}
func (v *Base62) Encode(id uint64) string {
result := make([]byte, 0, 11)
for id > 0 {
result = append(result, v.enc[id%size])
id /= size
}
sorts.Reverse(result)
return string(result)
}
func (v *Base62) Decode(data string) uint64 {
var id uint64
for _, r := range data {
id = id*size + uint64(bytes.IndexRune(v.enc, r))
}
return id
}