mirror of https://gitee.com/answerdev/answer.git
add en de short id
This commit is contained in:
parent
32cb89e9d4
commit
ffee84ced2
|
@ -1,5 +1,7 @@
|
|||
package uid
|
||||
|
||||
import "strconv"
|
||||
|
||||
const salt = int64(12345678)
|
||||
|
||||
var AlphanumericSet = []rune{
|
||||
|
@ -18,7 +20,7 @@ func init() {
|
|||
}
|
||||
|
||||
// NumToString num to string
|
||||
func NumToString(id int64) string {
|
||||
func NumToShortID(id int64) string {
|
||||
id = id + salt
|
||||
var code []rune
|
||||
for id > 0 {
|
||||
|
@ -30,7 +32,7 @@ func NumToString(id int64) string {
|
|||
}
|
||||
|
||||
// StringToNum string to num
|
||||
func StringToNum(code string) int64 {
|
||||
func ShortIDToNum(code string) int64 {
|
||||
var id int64
|
||||
runes := []rune(code)
|
||||
|
||||
|
@ -42,3 +44,15 @@ func StringToNum(code string) int64 {
|
|||
id = id - salt
|
||||
return id
|
||||
}
|
||||
|
||||
func EnShortID(id string) string {
|
||||
num, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return NumToShortID(num)
|
||||
}
|
||||
func DeShortID(sid string) string {
|
||||
num := ShortIDToNum(sid)
|
||||
return strconv.FormatInt(num, 10)
|
||||
}
|
||||
|
|
|
@ -5,11 +5,20 @@ import (
|
|||
"testing"
|
||||
)
|
||||
|
||||
func Test_getInviteCodeById(t *testing.T) {
|
||||
nums := []int64{0, 1, 10, 100, 1000, 10000, 100000, 10010000000001316, 10030000000001316}
|
||||
func Test_ShortID(t *testing.T) {
|
||||
nums := []int64{0, 1, 10, 100, 1000, 10000, 100000, 10010000000001316, 10030000000001316, 999999999999999999, 1999999999999999999}
|
||||
for _, num := range nums {
|
||||
code := NumToString(num)
|
||||
denum := StringToNum(code)
|
||||
code := NumToShortID(num)
|
||||
denum := ShortIDToNum(code)
|
||||
fmt.Println(num, code, denum)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_EnDeShortID(t *testing.T) {
|
||||
nums := []string{"0", "1", "10", "100", "1000", "10000", "100000", "1234567", "10010000000001316", "10030000000001316", "99999999999999999", "999999999999999999", "1999999999999999999"}
|
||||
for _, num := range nums {
|
||||
code := EnShortID(num)
|
||||
denum := DeShortID(code)
|
||||
fmt.Println(num, code, denum)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue