From 96c4edf226ef639c92f96f42c7c2a161ae0e1a66 Mon Sep 17 00:00:00 2001 From: Tony Holdstock-Brown Date: Sat, 13 Apr 2024 11:09:41 -0700 Subject: [PATCH] Add `ulid.Zero` and `.IsZero()` method (#112) * Add `uuid.Nil` and `.IsZero()` method This simplifies comparisons with empty ULIDs. Right now, most people are doing something like the following to check if a ULID is non-zero: ```go id.Compare(ulid.ULID{}) == 0 ``` This requires allocating a new empty ULID each time. Some packages avoid this by creating their own global (or private) nil ULIDs on initialization. This should be built in and simple for better perf & a cleaner API. * Update ulid.go * Update ulid.go * Update ulid.go * Update ulid_test.go * Update ulid_test.go --------- Co-authored-by: Peter Bourgon --- ulid.go | 8 ++++++++ ulid_test.go | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/ulid.go b/ulid.go index 2064dd4..77e9ddd 100644 --- a/ulid.go +++ b/ulid.go @@ -75,6 +75,9 @@ var ( // ErrScanValue is returned when the value passed to scan cannot be unmarshaled // into the ULID. ErrScanValue = errors.New("ulid: source value must be a string or byte slice") + + // Zero is a zero-value ULID. + Zero ULID ) // MonotonicReader is an interface that should yield monotonically increasing @@ -416,6 +419,11 @@ func (id ULID) Timestamp() time.Time { return Time(id.Time()) } +// IsZero returns true if the ULID is a zero-value ULID, i.e. ulid.Zero. +func (id ULID) IsZero() bool { + return id.Compare(Zero) == 0 +} + // maxTime is the maximum Unix time in milliseconds that can be // represented in a ULID. var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time() diff --git a/ulid_test.go b/ulid_test.go index 43f81c6..5ca70ae 100644 --- a/ulid_test.go +++ b/ulid_test.go @@ -454,6 +454,20 @@ func TestULIDTimestamp(t *testing.T) { } } +func TestZero(t *testing.T) { + t.Parallel() + + var id ulid.ULID + if ok := id.IsZero(); !ok { + t.Error(".IsZero: must return true for zero-value ULIDs, have false") + } + + id = ulid.MustNew(ulid.Now(), ulid.DefaultEntropy()) + if ok := id.IsZero(); ok { + t.Error(".IsZero: must return false for non-zero-value ULIDs, have true") + } +} + func TestEntropy(t *testing.T) { t.Parallel()