LEFT | RIGHT |
1 package trivial | 1 package trivial |
2 | 2 |
3 import ( | 3 import ( |
4 "crypto/rand" | 4 "crypto/rand" |
5 "fmt" | 5 "fmt" |
6 "io" | 6 "io" |
7 ) | 7 ) |
8 | 8 |
9 // UUID represent a universal identifier with 16 octets. | 9 // UUID represent a universal identifier with 16 octets. |
10 type UUID [16]byte | 10 type UUID [16]byte |
11 | 11 |
12 // NewUUID generates a new version 4 UUID relying only on random numbers. | 12 // NewUUID generates a new version 4 UUID relying only on random numbers. |
13 func NewUUID() (UUID, error) { | 13 func NewUUID() (UUID, error) { |
14 uuid := UUID{} | 14 uuid := UUID{} |
15 if _, err := io.ReadFull(rand.Reader, []byte(uuid[0:16])); err != nil { | 15 if _, err := io.ReadFull(rand.Reader, []byte(uuid[0:16])); err != nil { |
16 return UUID{}, err | 16 return UUID{}, err |
17 } | 17 } |
18 // Set version (4) and variant (2) according to RfC 4122. | 18 // Set version (4) and variant (2) according to RfC 4122. |
19 var version byte = 4 << 4 | 19 var version byte = 4 << 4 |
20 var variant byte = 8 << 4 | 20 var variant byte = 8 << 4 |
21 uuid[6] = version | (uuid[6] & 15) | 21 uuid[6] = version | (uuid[6] & 15) |
22 uuid[8] = variant | (uuid[8] & 15) | 22 uuid[8] = variant | (uuid[8] & 15) |
23 return uuid, nil | 23 return uuid, nil |
24 } | 24 } |
25 | 25 |
26 // Copy returns a copy of the UUID. | 26 // Copy returns a copy of the UUID. |
27 func (uuid UUID) Copy() UUID { | 27 func (uuid UUID) Copy() UUID { |
28 » raw := uuid.Raw() | 28 » uuidCopy := uuid |
29 » return UUID(raw) | 29 » return uuidCopy |
30 } | 30 } |
31 | 31 |
32 // Raw returns a copy of the UUID bytes. | 32 // Raw returns a copy of the UUID bytes. |
33 func (uuid UUID) Raw() [16]byte { | 33 func (uuid UUID) Raw() [16]byte { |
34 » var raw [16]byte | 34 » return [16]byte(uuid) |
35 » copy([]byte(raw[0:16]), []byte(uuid[0:16])) | |
36 » return raw | |
37 } | 35 } |
38 | 36 |
39 // String returns a hexadecimal string representation with | 37 // String returns a hexadecimal string representation with |
40 // standardized separators. | 38 // standardized separators. |
41 func (uuid UUID) String() string { | 39 func (uuid UUID) String() string { |
42 return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uu
id[8:10], uuid[10:16]) | 40 return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uu
id[8:10], uuid[10:16]) |
43 } | 41 } |
LEFT | RIGHT |