2013-02-28 13:28:48 +08:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
2013-08-26 13:41:58 +08:00
|
|
|
"strconv"
|
|
|
|
"sync/atomic"
|
2013-08-30 12:36:57 +08:00
|
|
|
"time"
|
2013-02-28 13:28:48 +08:00
|
|
|
)
|
|
|
|
|
2013-08-30 11:41:18 +08:00
|
|
|
var (
|
2013-12-26 15:28:42 +08:00
|
|
|
// Global ID generator
|
|
|
|
// Default is an autoincrement ID generator
|
2013-08-30 11:41:18 +08:00
|
|
|
IdGen IdGenerator
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
IdGen = NewAutoIncId()
|
|
|
|
}
|
|
|
|
|
2013-12-26 15:28:42 +08:00
|
|
|
// ID generator interface. Users can implament this for
|
|
|
|
// their own generator.
|
2013-02-28 13:28:48 +08:00
|
|
|
type IdGenerator interface {
|
2013-08-26 13:41:58 +08:00
|
|
|
Id() string
|
2013-02-28 13:28:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// AutoIncId
|
|
|
|
type autoincId struct {
|
2013-08-26 13:41:58 +08:00
|
|
|
value int64
|
2013-02-28 13:28:48 +08:00
|
|
|
}
|
|
|
|
|
2013-08-26 13:41:58 +08:00
|
|
|
func (ai *autoincId) Id() string {
|
|
|
|
next := atomic.AddInt64(&ai.value, 1)
|
|
|
|
return strconv.FormatInt(next, 10)
|
2013-02-28 13:28:48 +08:00
|
|
|
}
|
|
|
|
|
2019-02-28 10:11:17 +08:00
|
|
|
// NewAutoIncId returns an autoincrement ID generator
|
2013-02-28 13:28:48 +08:00
|
|
|
func NewAutoIncId() IdGenerator {
|
2013-08-26 13:41:58 +08:00
|
|
|
// we'll consider the nano fraction of a second at startup unique
|
|
|
|
// and count up from there.
|
|
|
|
return &autoincId{
|
|
|
|
value: int64(time.Now().Nanosecond()) << 32,
|
|
|
|
}
|
2013-02-28 13:28:48 +08:00
|
|
|
}
|