Skip to content

Commit 65298b4

Browse files
committed
feat: move uxid
1 parent 3013cb6 commit 65298b4

File tree

4 files changed

+104
-0
lines changed

4 files changed

+104
-0
lines changed

uxid/example/main.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/vitalvas/gokit/uxid"
7+
)
8+
9+
func main() {
10+
id := uxid.New().String()
11+
12+
fmt.Println("id:", id)
13+
fmt.Println("id len:", len(id))
14+
}

uxid/id.go

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package uxid
2+
3+
import (
4+
"math/rand"
5+
"strings"
6+
"time"
7+
)
8+
9+
type ID struct {
10+
ts int64
11+
rand int64
12+
}
13+
14+
const encodeDict = "0123456789abcdefghjkmnopqrstuvwxyz"
15+
16+
func init() {
17+
rand.Seed(time.Now().UTC().UnixNano())
18+
}
19+
20+
func New() ID {
21+
return NewWithTime(time.Now())
22+
}
23+
24+
func NewWithTime(t time.Time) ID {
25+
return ID{
26+
ts: t.UTC().UnixNano(),
27+
rand: rand.Int63(),
28+
}
29+
}
30+
31+
func (id ID) String() string {
32+
return encode(id.ts) + encode(id.rand)
33+
}
34+
35+
func encode(n int64) string {
36+
var chars = make([]string, 12, 12)
37+
38+
encodeDictSize := int64(len(encodeDict))
39+
40+
for i := len(chars) - 1; i >= 0; i-- {
41+
index := n % encodeDictSize
42+
chars[i] = string(encodeDict[index])
43+
n = n / encodeDictSize
44+
}
45+
46+
return strings.Join(chars, "")
47+
}

uxid/id_test.go

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package uxid
2+
3+
import (
4+
"testing"
5+
"time"
6+
)
7+
8+
func BenchmarkNew(b *testing.B) {
9+
b.RunParallel(func(pb *testing.PB) {
10+
for pb.Next() {
11+
_ = New()
12+
}
13+
})
14+
}
15+
16+
func BenchmarkNewWithTime(b *testing.B) {
17+
b.RunParallel(func(pb *testing.PB) {
18+
ts := time.Now()
19+
for pb.Next() {
20+
_ = NewWithTime(ts)
21+
}
22+
})
23+
}
24+
25+
func BenchmarkNewString(b *testing.B) {
26+
b.RunParallel(func(pb *testing.PB) {
27+
for pb.Next() {
28+
_ = New().String()
29+
}
30+
})
31+
}
32+
33+
func BenchmarkNewWithTimeString(b *testing.B) {
34+
b.RunParallel(func(pb *testing.PB) {
35+
ts := time.Now()
36+
for pb.Next() {
37+
_ = NewWithTime(ts).String()
38+
}
39+
})
40+
}

uxid/readme.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Globally Unique ID Generator
2+
3+
Package uxid is a globally unique id generator library, ready to safely be used directly in your server code.

0 commit comments

Comments
 (0)