Initial commit
This commit is contained in:
32
lib/idgen/gen.go
Normal file
32
lib/idgen/gen.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package idgen
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
lock sync.Mutex
|
||||
ts uint64 = uint64(time.Now().Unix())
|
||||
counter uint64 = 1
|
||||
counterMax uint64 = 1 << 28
|
||||
)
|
||||
|
||||
// Next can generate ~268M ints per second for ~1000 years.
|
||||
func Next() uint64 {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
tt := uint64(time.Now().Unix())
|
||||
if tt > ts {
|
||||
ts = tt
|
||||
counter = 1
|
||||
} else {
|
||||
counter++
|
||||
if counter == counterMax {
|
||||
panic("Too many IDs.")
|
||||
}
|
||||
}
|
||||
|
||||
return ts<<28 + counter
|
||||
}
|
||||
11
lib/idgen/gen_test.go
Normal file
11
lib/idgen/gen_test.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package idgen
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkNext(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user