Skip to content

Commit

Permalink
Add uuid.Nil and .IsZero() method
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
tonyhb committed Feb 10, 2024
1 parent a1d104f commit acbb2c3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions ulid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")

// Nil is an empty ULID, all zeros, useful when comparing nil ULIDs
Nil ULID
)

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

// IsZero returns whether the ULID is a zero-value, ie ulid.Nil.
func (id ULID) IsZero() bool {
return bytes.Compare(id[:], Nil[:]) == 0

Check failure on line 424 in ulid.go

View workflow job for this annotation

GitHub Actions / lint

should use bytes.Equal(id[:], Nil[:]) instead (S1004)
}

// 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()
Expand Down
14 changes: 14 additions & 0 deletions ulid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 empty ULIDs, have false")
}

id = ulid.MustNew(ulid.Now(), ulid.DefaultEntropy())
if ok := id.IsZero(); ok {
t.Error(".IsZero: must return false for non-nil ULIDs, have true")
}
}

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

Expand Down

0 comments on commit acbb2c3

Please sign in to comment.