forked from go-bond/bond
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
57 lines (44 loc) · 1.14 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package bond
import (
"fmt"
"math"
"sync"
"time"
"github.com/google/uuid"
)
type UniqueKeyGenerator[T any] interface {
Next() (T, error)
}
const NumberSequenceTimestampMask = 0xFFFFFFFFFF000000
const NumberSequenceBitShift = 24
const NumberSequenceSequenceNumberMask = 0x0000000000FFFFFF
type NumberSequence struct {
lastId uint64
mutex sync.Mutex
}
func (n *NumberSequence) Next() (uint64, error) {
n.mutex.Lock()
defer n.mutex.Unlock()
nextId := uint64(time.Now().Unix() << NumberSequenceBitShift)
if n.lastId&NumberSequenceTimestampMask == nextId&NumberSequenceTimestampMask {
if n.lastId&NumberSequenceSequenceNumberMask == NumberSequenceSequenceNumberMask {
return math.MaxUint64, fmt.Errorf("sequence number overflow")
}
nextId = n.lastId + 1
n.lastId = nextId
} else {
n.lastId = nextId
}
return nextId, nil
}
func (n *NumberSequence) Timestamp(ns uint64) uint64 {
return ns >> NumberSequenceBitShift
}
func (n *NumberSequence) SequenceNumber(ns uint64) uint64 {
return ns & NumberSequenceSequenceNumberMask
}
type UUIDGenerator struct {
}
func (n *UUIDGenerator) Next() (uuid.UUID, error) {
return uuid.New(), nil
}