-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
47 lines (39 loc) · 987 Bytes
/
crypto.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
package valkyrie
import (
"math/rand"
"sync"
"time"
"github.com/oklog/ulid/v2"
)
type safeUlid struct {
safe *safeMonotonicReader
t time.Time
monotonic *ulid.MonotonicEntropy
}
func (s *safeUlid) SafeMonotonic() ulid.ULID {
return ulid.MustNew(ulid.Timestamp(s.t), s.safe)
}
func (s *safeUlid) Monotonic() ulid.ULID {
return ulid.MustNew(ulid.Timestamp(s.t), s.monotonic)
}
// ULID Universally Unique Lexicographically Sortable Identifier
func ULID(t time.Time) *safeUlid {
src := rand.NewSource(time.Now().UnixNano())
entropy := rand.New(src)
monotonic := ulid.Monotonic(entropy, 0)
return &safeUlid{
safe: &safeMonotonicReader{MonotonicReader: monotonic},
t: t,
monotonic: monotonic,
}
}
type safeMonotonicReader struct {
mtx sync.Mutex
ulid.MonotonicReader
}
func (r *safeMonotonicReader) MonotonicRead(ms uint64, p []byte) (err error) {
r.mtx.Lock()
err = r.MonotonicReader.MonotonicRead(ms, p)
r.mtx.Unlock()
return err
}