...
1 package rand
2
3 import (
4 "encoding/hex"
5 "io"
6 )
7
8 const dash byte = '-'
9
10
11
12 type UUIDIdempotencyToken struct {
13 uuid *UUID
14 }
15
16
17
18 func NewUUIDIdempotencyToken(r io.Reader) *UUIDIdempotencyToken {
19 return &UUIDIdempotencyToken{uuid: NewUUID(r)}
20 }
21
22
23 func (u UUIDIdempotencyToken) GetIdempotencyToken() (string, error) {
24 return u.uuid.GetUUID()
25 }
26
27
28
29 type UUID struct {
30 randSrc io.Reader
31 }
32
33
34
35 func NewUUID(r io.Reader) *UUID {
36 return &UUID{randSrc: r}
37 }
38
39
40
41 func (r *UUID) GetUUID() (string, error) {
42 var b [16]byte
43 if _, err := io.ReadFull(r.randSrc, b[:]); err != nil {
44 return "", err
45 }
46 r.makeUUIDv4(b[:])
47 return format(b), nil
48 }
49
50
51
52 func (r *UUID) GetBytes() (u []byte, err error) {
53 u = make([]byte, 16)
54 if _, err = io.ReadFull(r.randSrc, u); err != nil {
55 return u, err
56 }
57 r.makeUUIDv4(u)
58 return u, nil
59 }
60
61 func (r *UUID) makeUUIDv4(u []byte) {
62
63 u[6] = (u[6] & 0x0f) | 0x40
64
65 u[8] = (u[8] & 0x3f) | 0x80
66 }
67
68
69
70
71 func format(u [16]byte) string {
72
73
74 var scratch [36]byte
75
76 hex.Encode(scratch[:8], u[0:4])
77 scratch[8] = dash
78 hex.Encode(scratch[9:13], u[4:6])
79 scratch[13] = dash
80 hex.Encode(scratch[14:18], u[6:8])
81 scratch[18] = dash
82 hex.Encode(scratch[19:23], u[8:10])
83 scratch[23] = dash
84 hex.Encode(scratch[24:], u[10:])
85
86 return string(scratch[:])
87 }
88
View as plain text