-
Notifications
You must be signed in to change notification settings - Fork 0
/
id.go
52 lines (44 loc) · 1007 Bytes
/
id.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
package gorand
import (
"bytes"
"io"
"time"
)
var localID [9]byte
var defaultID = [9]byte{'D', 'e', 'f', 'a', 'u', 'l', 't', 'I', 'D'}
// Initializes the value for the local process run identifier
func init() {
buf, err := GetBytes(9)
if err != nil {
localID = defaultID
} else {
_, err = io.ReadFull(bytes.NewBuffer(buf), localID[:])
if err != nil {
localID = defaultID
}
}
}
// ID generates a [64]byte random value, using time and local identifier into it.
//
// First (most-significative) 15 bytes: time value
// Next 9 bytes: Local process randomly-generated identifier
// Next 40 bytes: Random value
func ID() (id [64]byte, err error) {
var buf []byte
// Time part
now, err := time.Now().MarshalBinary()
if err != nil {
return
}
buf = append(buf, now[:15]...)
// Local ID part
buf = append(buf, localID[:]...)
// Random value
r, err := GetBytes(40)
if err != nil {
return
}
buf = append(buf, r...)
_, err = io.ReadFull(bytes.NewBuffer(buf), id[:])
return
}