Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ulid.Nil and .IsZero() method #112

Merged
merged 6 commits into from
Apr 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
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
peterbourgon marked this conversation as resolved.
Show resolved Hide resolved
)

// 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.
peterbourgon marked this conversation as resolved.
Show resolved Hide resolved
func (id ULID) IsZero() bool {
return bytes.Equal(id[:], Nil[:])
peterbourgon marked this conversation as resolved.
Show resolved Hide resolved
}

// 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")
peterbourgon marked this conversation as resolved.
Show resolved Hide resolved
}

id = ulid.MustNew(ulid.Now(), ulid.DefaultEntropy())
if ok := id.IsZero(); ok {
t.Error(".IsZero: must return false for non-nil ULIDs, have true")
peterbourgon marked this conversation as resolved.
Show resolved Hide resolved
}
}

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

Expand Down
Loading