Skip to content

Commit 1eee168

Browse files
authored
Merge pull request #2 from segmentfault/utils/id
add utils id
2 parents f734f4a + 3b72d14 commit 1eee168

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

utils/id.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package utils
2+
3+
var ShortIDSwitch = false
4+
5+
var AlphanumericSet = []rune{
6+
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
7+
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
8+
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
9+
}
10+
11+
var AlphanumericIndex map[rune]int
12+
13+
func init() {
14+
AlphanumericIndex = make(map[rune]int, len(AlphanumericSet))
15+
for i, ru := range AlphanumericSet {
16+
AlphanumericIndex[ru] = i
17+
}
18+
}
19+
20+
func EnShortID(id int64, salt int64) string {
21+
id = id + salt
22+
var code []rune
23+
for id > 0 {
24+
idx := id % int64(len(AlphanumericSet))
25+
code = append(code, AlphanumericSet[idx])
26+
id = id / int64(len(AlphanumericSet))
27+
}
28+
return string(code)
29+
}
30+
func DeShortID(code string, salt int64) int64 {
31+
var id int64
32+
runes := []rune(code)
33+
for i := len(runes) - 1; i >= 0; i-- {
34+
ru := runes[i]
35+
idx := AlphanumericIndex[ru]
36+
id = id*int64(len(AlphanumericSet)) + int64(idx)
37+
}
38+
id = id - salt
39+
return id
40+
}

utils/id_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package utils
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func Test_ShortID(t *testing.T) {
9+
nums := []int64{
10+
10010000000000001, 10010000000000002, 10010000000000003, 10010000000000004,
11+
10030000000000689, 10010000000000676, 10020000000000658, 10020000000000654,
12+
10030000009000689, 10010000009000676, 10020000009000658, 10020000009999999,
13+
10030000090000689, 10010000090000676, 10020000090000658, 10020000099999999,
14+
10030000900000689, 10010000900000676, 10020000900000658, 10020000999999999,
15+
10030009000000689, 10010009000000676, 10020009000000658, 10020009999999999,
16+
10030090000000689, 10010090000000676, 10020090000000658, 10020099999999999,
17+
10030900000000689, 10010900000000676, 10020900000000658, 10020999999999999,
18+
10039000000000689, 10019000000000676, 10029000000000658, 10029999999999999,
19+
10610000000000689, 10610000000000676, 10610000000000658, 10610000000000654,
20+
19990000000000689, 19990000000000676, 19990000000000658, 19990000000000654,
21+
}
22+
for _, num := range nums {
23+
code := EnShortID(num, 0)
24+
denum := DeShortID(code, 0)
25+
fmt.Println(num, code, denum)
26+
}
27+
}

0 commit comments

Comments
 (0)