]>
Commit | Line | Data |
---|---|---|
1 | package uuid | |
2 | ||
3 | import ( | |
4 | "crypto/rand" | |
5 | "encoding/hex" | |
6 | "fmt" | |
7 | ) | |
8 | ||
9 | // GenerateUUID is used to generate a random UUID | |
10 | func GenerateUUID() (string, error) { | |
11 | buf := make([]byte, 16) | |
12 | if _, err := rand.Read(buf); err != nil { | |
13 | return "", fmt.Errorf("failed to read random bytes: %v", err) | |
14 | } | |
15 | ||
16 | return FormatUUID(buf) | |
17 | } | |
18 | ||
19 | func FormatUUID(buf []byte) (string, error) { | |
20 | if len(buf) != 16 { | |
21 | return "", fmt.Errorf("wrong length byte slice (%d)", len(buf)) | |
22 | } | |
23 | ||
24 | return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", | |
25 | buf[0:4], | |
26 | buf[4:6], | |
27 | buf[6:8], | |
28 | buf[8:10], | |
29 | buf[10:16]), nil | |
30 | } | |
31 | ||
32 | func ParseUUID(uuid string) ([]byte, error) { | |
33 | if len(uuid) != 36 { | |
34 | return nil, fmt.Errorf("uuid string is wrong length") | |
35 | } | |
36 | ||
37 | hyph := []byte("-") | |
38 | ||
39 | if uuid[8] != hyph[0] || | |
40 | uuid[13] != hyph[0] || | |
41 | uuid[18] != hyph[0] || | |
42 | uuid[23] != hyph[0] { | |
43 | return nil, fmt.Errorf("uuid is improperly formatted") | |
44 | } | |
45 | ||
46 | hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36] | |
47 | ||
48 | ret, err := hex.DecodeString(hexStr) | |
49 | if err != nil { | |
50 | return nil, err | |
51 | } | |
52 | if len(ret) != 16 { | |
53 | return nil, fmt.Errorf("decoded hex is the wrong length") | |
54 | } | |
55 | ||
56 | return ret, nil | |
57 | } |