@@ -2,6 +2,22 @@ package miniid
22
33import "sync/atomic"
44
5+ const (
6+ Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
7+ base = uint64 (len (Alphabet ))
8+ )
9+
10+ var index = func () [256 ]int {
11+ var index [256 ]int
12+ for i := range index {
13+ index [i ] = - 1
14+ }
15+ for i , c := range Alphabet {
16+ index [c ] = i
17+ }
18+ return index
19+ }()
20+
521// Encode number in base62.
622func Encode (n uint64 ) string {
723 return encodeBase62 (n )
@@ -12,6 +28,20 @@ func EncodeFixed(n uint64, length int) string {
1228 return encodeFixedBase62 (n , length )
1329}
1430
31+ // Decode converts a base62-encoded string back into a uint64 number.
32+ // It panics if the input contains characters not in the base62 alphabet.
33+ func Decode (s string ) uint64 {
34+ var n uint64
35+ for i := 0 ; i < len (s ); i ++ {
36+ val := index [s [i ]]
37+ if val < 0 {
38+ panic ("invalid base62 character" )
39+ }
40+ n = n * base + uint64 (val )
41+ }
42+ return n
43+ }
44+
1545// Generator can encode integers into base62 strings.
1646type Generator struct {
1747 currID atomic.Int64
@@ -31,11 +61,8 @@ func (g *Generator) Next() string {
3161}
3262
3363func encodeBase62 (num uint64 ) string {
34- const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
35- const base = uint64 (len (alphabet ))
36-
3764 if num == 0 {
38- return string (alphabet [0 ])
65+ return string (Alphabet [0 ])
3966 }
4067
4168 const maxLen = 16
@@ -44,19 +71,16 @@ func encodeBase62(num uint64) string {
4471
4572 for ; num > 0 ; i -- {
4673 rem := num % base
47- result [i ] = alphabet [rem ]
74+ result [i ] = Alphabet [rem ]
4875 num /= base
4976 }
5077 return string (result [i + 1 :])
5178}
5279
5380func encodeFixedBase62 (num uint64 , length int ) string {
54- const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
55- const base = uint64 (len (alphabet ))
56-
5781 buf := make ([]byte , length )
5882 for i := length - 1 ; i >= 0 ; i -- {
59- buf [i ] = alphabet [num % base ]
83+ buf [i ] = Alphabet [num % base ]
6084 num /= base
6185 }
6286 return string (buf )
0 commit comments