jldb/lib/idgen/gen.go

33 lines
473 B
Go
Raw Permalink Normal View History

2023-10-13 09:43:27 +00:00
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
}