-
Notifications
You must be signed in to change notification settings - Fork 4
/
uuid.go
42 lines (35 loc) · 991 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
package sop
import (
"bytes"
"time"
"github.com/google/uuid"
)
// UUID type.
type UUID uuid.UUID
// NewUUID returns a new UUID. Will retry after sleep of 1 milli if an error occurs.
// Guaranteed no panic by sleeping/retry, and only does after exhausting 10 attempts.
func NewUUID() UUID {
// In the case of generating new UUID errored, we just need to retry because
// generating UUID is a must.
var err error
for i := 0; i < 10; i++ {
var id uuid.UUID
id, err = uuid.NewRandom()
if err == nil {
return UUID(id)
}
// Sleep 1 millisecond then retry to generate new UUID.
time.Sleep(time.Duration(1 * time.Millisecond))
}
// Panic if still can't generate UUID after 10 retries. Should never happen but in case.
panic(err)
}
// NillUUID is an empty UUID.
var NilUUID UUID
func (id UUID) IsNil() bool {
return bytes.Compare(id[:], NilUUID[:]) == 0
}
// String converts UUID to its string representation.
func (id UUID) String() string {
return string(id[:])
}