Skip to content

Commit

Permalink
Merge pull request #2 from segmentfault/utils/id
Browse files Browse the repository at this point in the history
add utils id
  • Loading branch information
aichy126 authored Mar 20, 2023
2 parents f734f4a + 3b72d14 commit 1eee168
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
40 changes: 40 additions & 0 deletions utils/id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package utils

var ShortIDSwitch = false

var AlphanumericSet = []rune{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'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',
'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',
}

var AlphanumericIndex map[rune]int

func init() {
AlphanumericIndex = make(map[rune]int, len(AlphanumericSet))
for i, ru := range AlphanumericSet {
AlphanumericIndex[ru] = i
}
}

func EnShortID(id int64, salt int64) string {
id = id + salt
var code []rune
for id > 0 {
idx := id % int64(len(AlphanumericSet))
code = append(code, AlphanumericSet[idx])
id = id / int64(len(AlphanumericSet))
}
return string(code)
}
func DeShortID(code string, salt int64) int64 {
var id int64
runes := []rune(code)
for i := len(runes) - 1; i >= 0; i-- {
ru := runes[i]
idx := AlphanumericIndex[ru]
id = id*int64(len(AlphanumericSet)) + int64(idx)
}
id = id - salt
return id
}
27 changes: 27 additions & 0 deletions utils/id_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package utils

import (
"fmt"
"testing"
)

func Test_ShortID(t *testing.T) {
nums := []int64{
10010000000000001, 10010000000000002, 10010000000000003, 10010000000000004,
10030000000000689, 10010000000000676, 10020000000000658, 10020000000000654,
10030000009000689, 10010000009000676, 10020000009000658, 10020000009999999,
10030000090000689, 10010000090000676, 10020000090000658, 10020000099999999,
10030000900000689, 10010000900000676, 10020000900000658, 10020000999999999,
10030009000000689, 10010009000000676, 10020009000000658, 10020009999999999,
10030090000000689, 10010090000000676, 10020090000000658, 10020099999999999,
10030900000000689, 10010900000000676, 10020900000000658, 10020999999999999,
10039000000000689, 10019000000000676, 10029000000000658, 10029999999999999,
10610000000000689, 10610000000000676, 10610000000000658, 10610000000000654,
19990000000000689, 19990000000000676, 19990000000000658, 19990000000000654,
}
for _, num := range nums {
code := EnShortID(num, 0)
denum := DeShortID(code, 0)
fmt.Println(num, code, denum)
}
}

0 comments on commit 1eee168

Please sign in to comment.