-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathid_generator_string.go
76 lines (61 loc) · 1.38 KB
/
id_generator_string.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
package luigi
import (
"strconv"
"strings"
"sync/atomic"
)
func (this UIDGenerator) GenerateString() (string, error) {
now, err := this.getTimeNanoseconds()
if err != nil {
return "", err
}
currentID := this.getNextUintID()
return this.getUIDString(now, currentID), nil
}
func (this UIDGenerator) GenerateSliceString(n uint32) ([]string, error) {
uids := make([]string, n, n)
id := atomic.AddUint32(this.sequence, n)
var (
currentID uint64
now uint64
err error
)
for i := uint32(0); i < n; i++ {
currentID = uint64((id - (n - i - 1)) & maxSequence)
if now, err = this.getTimeNanoseconds(); err != nil {
return nil, err
}
uids[i] = this.getUIDString(now, currentID)
}
return uids, nil
}
func (this UIDGenerator) FillChannelString(ch chan<- string) chan error {
var (
err error
errChannel = make(chan error)
uid string
)
go func() {
defer func() {
if rec := recover(); rec != nil {
close(errChannel)
return
}
}()
for {
uid, err = this.GenerateString()
if err != nil {
errChannel <- err
close(errChannel)
close(ch)
return
}
ch <- uid
}
}()
return errChannel
}
func (this UIDGenerator) getUIDString(now, currentID uint64) string {
currentNodeID := uint64(this.nodeID | currentID)
return strings.Join([]string{strconv.FormatUint(now, 10), strconv.FormatUint(currentNodeID, 10)}, "")
}