33 lines
473 B
Go
33 lines
473 B
Go
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
|
|
}
|