Skip to content

Commit 96c4edf

Browse files
tonyhbpeterbourgon
andauthored
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 <peterbourgon@users.noreply.github.com>
1 parent 8b543f4 commit 96c4edf

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

ulid.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ var (
7575
// ErrScanValue is returned when the value passed to scan cannot be unmarshaled
7676
// into the ULID.
7777
ErrScanValue = errors.New("ulid: source value must be a string or byte slice")
78+
79+
// Zero is a zero-value ULID.
80+
Zero ULID
7881
)
7982

8083
// MonotonicReader is an interface that should yield monotonically increasing
@@ -416,6 +419,11 @@ func (id ULID) Timestamp() time.Time {
416419
return Time(id.Time())
417420
}
418421

422+
// IsZero returns true if the ULID is a zero-value ULID, i.e. ulid.Zero.
423+
func (id ULID) IsZero() bool {
424+
return id.Compare(Zero) == 0
425+
}
426+
419427
// maxTime is the maximum Unix time in milliseconds that can be
420428
// represented in a ULID.
421429
var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time()

ulid_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,20 @@ func TestULIDTimestamp(t *testing.T) {
454454
}
455455
}
456456

457+
func TestZero(t *testing.T) {
458+
t.Parallel()
459+
460+
var id ulid.ULID
461+
if ok := id.IsZero(); !ok {
462+
t.Error(".IsZero: must return true for zero-value ULIDs, have false")
463+
}
464+
465+
id = ulid.MustNew(ulid.Now(), ulid.DefaultEntropy())
466+
if ok := id.IsZero(); ok {
467+
t.Error(".IsZero: must return false for non-zero-value ULIDs, have true")
468+
}
469+
}
470+
457471
func TestEntropy(t *testing.T) {
458472
t.Parallel()
459473

0 commit comments

Comments
 (0)