-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.go
More file actions
41 lines (36 loc) · 821 Bytes
/
encode.go
File metadata and controls
41 lines (36 loc) · 821 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
package hqid7
import (
"errors"
"github.com/mr-tron/base58"
"strings"
)
func NewString() string {
return EncodeBase58(MustUUID7())
}
func encodeBase58Raw(u UUID) string {
return base58.Encode(u[:])
}
func EncodeBase58(u UUID) string {
s := base58.Encode(u[:])
if len(s) != 22 {
s = strings.Repeat("1", 22-len(s)) + s // pad with leading "zeroes" (1 in BTC base58)
}
return s[0:9] + "_" + s[9:]
}
func DecodeBase58(s string) (UUID, error) {
if len(s) != 23 {
return UUID{}, errors.New("hqid7 base58: invalid length")
}
if s[9] != '_' {
return UUID{}, errors.New("hqid7 base58: invalid separator")
}
s = s[0:9] + s[10:]
d, err := base58.Decode(s)
if err != nil {
return UUID{}, err
}
if len(d) > 16 {
d = d[len(d)-16:] // remove leading "zeroes" (1 in BTC base58)
}
return UUID(d), nil
}