-
Notifications
You must be signed in to change notification settings - Fork 3
/
id.go
83 lines (68 loc) · 1.89 KB
/
id.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package idgen
import (
"errors"
"io"
"math"
"math/rand"
"strings"
"sync"
"time"
"github.com/oklog/ulid"
)
const (
// SeparatorByte is the byte representation of the separator '_' character.
SeparatorByte = byte('_')
// SeparatorString is the string representation of the separator '_' character.
SeparatorString = string(SeparatorByte)
)
var (
// ErrMalformed represents and error that is returned in case of malformed ulids
ErrMalformed = errors.New("idgen: malformed ulid")
)
// New generates a lexically sorted, url safe Id with a prefix.
// Eg: cus_JSfjkdjf333j46, i.e. {prefix}_{ulid}
func New(prefix string) string {
ent := getEntropy()
res := prefix + SeparatorString + ulid.MustNew(ulid.Now(), ent).String()
putEntropy(ent)
return res
}
var entropyPool = sync.Pool{
New: func() interface{} {
ns := time.Now().UnixNano()
return ulid.Monotonic(rand.New(rand.NewSource(ns)), uint64(ns)%math.MaxUint32)
},
}
func getEntropy() io.Reader {
return entropyPool.Get().(io.Reader)
}
func putEntropy(r io.Reader) {
entropyPool.Put(r)
}
// Generator generates ids with the provided prefix
type Generator struct {
Prefix string
}
// New generates a lexically sorted, url safe Id with available prefix
func (p Generator) New() string {
return New(p.Prefix)
}
// Prefix returns the prefix of the id. Id should be of type {prefix}{Separator}*
// If id is malformed it returns an empty string.
func Prefix(id string) string {
i := strings.IndexByte(id, SeparatorByte)
if i < 0 {
return ""
}
return id[:i]
}
// Time returns the Unix time in milliseconds encoded in the id.
// id should be of the form {prefix}{Separator}{ulid}. The prefix and separator are optional.
// ErrMalformed is returned in case of a malformed id.
func Time(id string) (uint64, error) {
uid, err := ulid.Parse(id[strings.IndexByte(id, SeparatorByte)+1:])
if err != nil {
return 0, ErrMalformed
}
return uid.Time(), nil
}