Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 71 additions & 9 deletions ulid.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,20 @@ func MustNew(ms uint64, entropy io.Reader) ULID {
// MustNewDefault is a convenience function equivalent to MustNew with
// DefaultEntropy as the entropy. It may panic if the given time.Time is too
// large or too small.
func MustNewDefault(t time.Time) ULID {
return MustNew(Timestamp(t), defaultEntropy)
func MustNewDefault(t time.Time) (id ULID) {
ms := Timestamp(t)
if err := id.SetTime(ms); err != nil {
panic(err)
}
if err := defaultEntropy.monotonicRead(ms, id[6:]); err != nil {
panic(err)
}
return id
}

var defaultEntropy = func() io.Reader {
var defaultEntropy = func() *lockedMonotonicEntropy {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
return &LockedMonotonicReader{MonotonicReader: Monotonic(rng, 0)}
return &lockedMonotonicEntropy{monotonic: Monotonic(rng, 0)}
}()

// DefaultEntropy returns a thread-safe per process monotonically increasing
Expand All @@ -145,11 +152,9 @@ func DefaultEntropy() io.Reader {

// Make returns a ULID with the current time in Unix milliseconds and
// monotonically increasing entropy for the same millisecond.
// It is safe for concurrent use, leveraging a sync.Pool underneath for minimal
// contention.
func Make() (id ULID) {
// NOTE: MustNew can't panic since DefaultEntropy never returns an error.
return MustNew(Now(), defaultEntropy)
// It is safe for concurrent use.
func Make() ULID {
return MustNewDefault(time.Now())
}

// Parse parses an encoded ULID, returning an error in case of failure.
Expand Down Expand Up @@ -630,6 +635,63 @@ func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error)
return err
}

// lockedMonotonicEntropy serializes access to the wrapped monotonic source.
type lockedMonotonicEntropy struct {
mu sync.Mutex
monotonic *MonotonicEntropy
seed [10]byte
zeroSeed bool // True until a valid zero seed is incremented.
}

func (r *lockedMonotonicEntropy) Read(p []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.monotonic.Read(p)
}

// MonotonicRead synchronizes calls to the wrapped monotonic source.
func (r *lockedMonotonicEntropy) MonotonicRead(ms uint64, p []byte) error {
r.mu.Lock()
err := r.monotonicReadLocked(ms, p, p, false)
r.mu.Unlock()
return err
}

// monotonicRead uses wrapper-owned storage so the returned ULID's entropy
// slice never reaches the wrapped reader interface.
func (r *lockedMonotonicEntropy) monotonicRead(ms uint64, p []byte) error {
r.mu.Lock()
err := r.monotonicReadLocked(ms, p, r.seed[:], true)
r.mu.Unlock()
return err
}

// monotonicReadLocked applies the shared entropy state transition
// while r.mu is held.
func (r *lockedMonotonicEntropy) monotonicReadLocked(ms uint64, p, seed []byte, copySeedToOutput bool) error {
if r.zeroSeed && r.monotonic.ms == ms {
return r.increment(p)
}

err := r.monotonic.MonotonicRead(ms, seed)
if copySeedToOutput {
copy(p, seed)
}
if err == nil {
r.zeroSeed = r.monotonic.ms == ms && r.monotonic.entropy.IsZero()
}
return err
}

func (r *lockedMonotonicEntropy) increment(p []byte) error {
err := r.monotonic.increment()
r.monotonic.entropy.AppendTo(p)
if r.zeroSeed && (err == nil || err == ErrMonotonicOverflow) {
r.zeroSeed = false
}
return err
}

// increment the previous entropy number with a random number
// of up to m.inc (inclusive).
func (m *MonotonicEntropy) increment() error {
Expand Down
101 changes: 101 additions & 0 deletions ulid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"math"
"math/rand"
"strings"
"sync"
"testing"
"testing/iotest"
"testing/quick"
Expand Down Expand Up @@ -72,6 +73,97 @@ func TestMake(t *testing.T) {
}
}

func TestMakeAllocations(t *testing.T) {
// One measured call per run prevents AllocsPerRun's integer average from rounding down.
for i := 0; i < 1000; i++ {
allocs := testing.AllocsPerRun(1, func() {
benchmarkMakeSink = ulid.Make()
})
if benchmarkMakeSink.IsZero() {
t.Fatal("Make returned the zero ULID")
}
if allocs != 0 {
t.Fatalf("Make allocated %g times per call, want 0", allocs)
}
}
}

func TestDefaultConstructorsShareEntropy(t *testing.T) {
first := ulid.Make()
ms := first.Time()

second, err := ulid.New(ms, ulid.DefaultEntropy())
if err != nil {
t.Fatal(err)
}
third := ulid.MustNew(ms, ulid.DefaultEntropy())
fourth := ulid.MustNewDefault(ulid.Time(ms))

for _, pair := range [][2]ulid.ULID{{first, second}, {second, third}, {third, fourth}} {
if pair[0].Compare(pair[1]) >= 0 {
t.Fatalf("default entropy order: %v is not before %v", pair[0], pair[1])
}
}
}

func TestDefaultEntropyConcurrent(t *testing.T) {
const (
goroutines = 16
calls = 16
)

ms := ulid.Now()
start := make(chan struct{})
ids := make(chan ulid.ULID, goroutines*calls)
errs := make(chan error, goroutines+1)
var wg sync.WaitGroup

wg.Add(1)
go func() {
defer wg.Done()
<-start
_, err := io.ReadFull(ulid.DefaultEntropy(), make([]byte, 1<<20))
errs <- err
}()

for i := 0; i < goroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
for j := 0; j < calls; j++ {
id, err := ulid.New(ms, ulid.DefaultEntropy())
if err != nil {
errs <- err
return
}
ids <- id
}
}()
}

close(start)
wg.Wait()
close(ids)
close(errs)
for err := range errs {
if err != nil {
t.Error(err)
}
}

seen := make(map[ulid.ULID]struct{}, goroutines*calls)
for id := range ids {
if _, ok := seen[id]; ok {
t.Errorf("duplicate ULID from concurrent default entropy: %v", id)
}
seen[id] = struct{}{}
}
if got, want := len(seen), goroutines*calls; got != want {
t.Errorf("got %d distinct ULIDs, want %d", got, want)
}
}

func TestMustNew(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -711,6 +803,15 @@ func BenchmarkMustNew(b *testing.B) {
})
}

var benchmarkMakeSink ulid.ULID

func BenchmarkMake(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
benchmarkMakeSink = ulid.Make()
}
}

func benchmarkMakeULID(b *testing.B, f func(uint64, io.Reader)) {
b.ReportAllocs()
b.SetBytes(int64(len(ulid.ULID{})))
Expand Down
Loading