-
Notifications
You must be signed in to change notification settings - Fork 106
/
guid.go
79 lines (62 loc) · 1.65 KB
/
guid.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package nsqd
// the core algorithm here was borrowed from:
// Blake Mizerany's `noeqd` https://github.com/bmizerany/noeqd
// and indirectly:
// Twitter's `snowflake` https://github.com/twitter/snowflake
// only minor cleanup and changes to introduce a type, combine the concept
// of workerID + datacenterId into a single identifier, and modify the
// behavior when sequences rollover for our specific implementation needs
import (
"encoding/hex"
"errors"
"time"
)
const (
workerIDBits = uint64(10)
sequenceBits = uint64(12)
workerIDShift = sequenceBits
timestampShift = sequenceBits + workerIDBits
sequenceMask = int64(-1) ^ (int64(-1) << sequenceBits)
// Tue, 21 Mar 2006 20:50:14.000 GMT
twepoch = int64(1288834974657)
)
var ErrTimeBackwards = errors.New("time has gone backwards")
var ErrSequenceExpired = errors.New("sequence expired")
type guid int64
type guidFactory struct {
sequence int64
lastTimestamp int64
}
func (f *guidFactory) NewGUID(workerID int64) (guid, error) {
ts := time.Now().UnixNano() / 1e6
if ts < f.lastTimestamp {
return 0, ErrTimeBackwards
}
if f.lastTimestamp == ts {
f.sequence = (f.sequence + 1) & sequenceMask
if f.sequence == 0 {
return 0, ErrSequenceExpired
}
} else {
f.sequence = 0
}
f.lastTimestamp = ts
id := ((ts - twepoch) << timestampShift) |
(workerID << workerIDShift) |
f.sequence
return guid(id), nil
}
func (g guid) Hex() MessageID {
var h MessageID
var b [8]byte
b[0] = byte(g >> 56)
b[1] = byte(g >> 48)
b[2] = byte(g >> 40)
b[3] = byte(g >> 32)
b[4] = byte(g >> 24)
b[5] = byte(g >> 16)
b[6] = byte(g >> 8)
b[7] = byte(g)
hex.Encode(h[:], b[:])
return h
}