/
uuid.go
57 lines (43 loc) · 1.26 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
// Package uuid is a simple library for generating RFC4122 compliant universally unique
// identifiers.
package uuid
import (
"crypto/rand"
"fmt"
)
const (
stringFormat = "%8x-%4x-%4x-%4x-%12x"
)
var defaultConfiguration Configuration = Configuration{
Version: 4,
RandomReader: rand.Read,
}
var defaultGenerator *Generator
// Generate provides a Version 4 random UUID
func Generate() UUID {
var err error
if defaultGenerator == nil {
defaultGenerator, err = NewGenerator(defaultConfiguration)
if err != nil {
panic(fmt.Sprintf("Unable to create default generator: %s", err))
}
}
return defaultGenerator.Generate()
}
// A UUID is a unique identifier.
type UUID []byte
// String provides a string representation of a UUID using the established
// dashed format.
func (id UUID) String() string {
bs := []byte(id)
return fmt.Sprintf(stringFormat, bs[0:4], bs[4:6], bs[6:8], bs[8:10], bs[10:])
}
// Parse returns a UUID from a given string
func Parse(id string) (uuid UUID, err error) {
var a, b, c, d, e []byte
_, err = fmt.Sscanf(id, stringFormat, &a, &b, &c, &d, &e)
uuid = append(append(append(append(a, b...), c...), d...), e...)
return uuid, err
}
// Version of the UUID
func (id UUID) Version() Version { return Version((id[6] & 0xF0) >> 4) }