-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
35 lines (29 loc) · 858 Bytes
/
util.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
package ulidutil
import (
"crypto/rand"
"io"
"sync"
"time"
"github.com/oklog/ulid/v2"
)
// NewString returns an ULID as a string, with the current time. It is safe for concurrent use
func NewString() string {
return ulid.MustNew(ulid.Timestamp(time.Now()), SecureEntropy()).String()
}
// NewStringWithTime returns an ULID as a string, with the given time. Panic on failure.
func NewStringWithTime(t time.Time) string {
return ulid.MustNew(ulid.Timestamp(t), SecureEntropy()).String()
}
var (
secureEntropy io.Reader
secureEntropyOnce sync.Once
)
// SecureEntropy returns a thread-safe per process monotonically increasing secure entropy source
func SecureEntropy() io.Reader {
secureEntropyOnce.Do(func() {
secureEntropy = &ulid.LockedMonotonicReader{
MonotonicReader: ulid.Monotonic(rand.Reader, 0),
}
})
return secureEntropy
}