-
Notifications
You must be signed in to change notification settings - Fork 0
/
uuid.go
46 lines (40 loc) · 936 Bytes
/
uuid.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
package util
import (
"crypto/rand"
"encoding/hex"
"io"
)
//see https://github.com/google/uuid
var (
rander = rand.Reader
)
type UUID [16]byte
// NewRandomUUID returns a UUID based on bytes read from crypto.Rand
func NewRandomUUID() UUID {
var uuid UUID
_, err := io.ReadFull(rander, uuid[:])
if err != nil {
return UUID{}
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid
}
// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// , or "" if uuid is invalid.
func (uuid UUID) String() string {
var buf [36]byte
encodeHex(buf[:], uuid)
return string(buf[:])
}
func encodeHex(dst []byte, uuid UUID) {
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
}