-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid64.go
69 lines (53 loc) · 1.26 KB
/
id64.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
package id64
import (
"sync/atomic"
"time"
"github.com/kokizzu/gotro/S"
"github.com/kpango/fastime"
)
var lastSec uint32
var Gen *Generator
var offset2021 uint32 // MinDateOffset = Offset2020.Unix() or MinNanoDateOffset = Offset2020.UnixNano()
func init() {
offset2021 = uint32(time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC).Unix())
Gen = &Generator{}
}
func ID() id64 {
return Gen.ID()
}
func UID() uint64 {
return uint64(Gen.ID())
}
func SID() string {
return Gen.ID().String()
}
func FromStr(sid string) id64 {
dec, ok := S.DecodeCB63[int64](sid)
if !ok {
return 0
}
return id64(dec)
}
type Generator struct {
AtomicCounter uint32
}
func (gen *Generator) ID() id64 {
now := uint32(fastime.UnixNow())
counter := atomic.AddUint32(&gen.AtomicCounter, 1)
if now != lastSec {
atomic.SwapUint32(&lastSec, now)
atomic.CompareAndSwapUint32(&gen.AtomicCounter, counter, 0)
counter = atomic.AddUint32(&gen.AtomicCounter, 1)
}
return id64((uint64(lastSec-offset2021) << 32) + uint64(counter))
}
type id64 uint64
func (i id64) Time() time.Time {
return time.Unix(int64(i>>32)+int64(offset2021), 0)
}
func (i id64) Counter() uint32 {
return uint32(i % (256 * 256 * 256 * 256))
}
func (i id64) String() string {
return S.EncodeCB63(int64(i), 0)
}