From 3b72d147f6b20eee91c40eb7cf5b7f014331529d Mon Sep 17 00:00:00 2001 From: aichy126 <16996097+aichy126@users.noreply.github.com> Date: Mon, 20 Mar 2023 10:48:09 +0800 Subject: [PATCH] add utils id --- utils/id.go | 40 ++++++++++++++++++++++++++++++++++++++++ utils/id_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 utils/id.go create mode 100644 utils/id_test.go diff --git a/utils/id.go b/utils/id.go new file mode 100644 index 0000000..3ff88a0 --- /dev/null +++ b/utils/id.go @@ -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 +} diff --git a/utils/id_test.go b/utils/id_test.go new file mode 100644 index 0000000..8387eb2 --- /dev/null +++ b/utils/id_test.go @@ -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) + } +}