Skip to content

Commit

Permalink
[time] UnixNano.Truncate should not panic on zero duration (#3571)
Browse files Browse the repository at this point in the history
  • Loading branch information
vdarulis authored Jun 25, 2021
1 parent 078564d commit 1c1a7ad
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/x/time/unix_nano.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ func ToUnixNano(t time.Time) UnixNano {
}

// Truncate returns the result of rounding u down to a multiple of d.
// If d <= 0, Truncate returns u unchanged.
func (u UnixNano) Truncate(d time.Duration) UnixNano {
if d <= 0 {
return u
}

duration := UnixNano(d)
return (u / duration) * duration
}
Expand Down
9 changes: 9 additions & 0 deletions src/x/time/unix_nano_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,12 @@ func TestCompareTimes(t *testing.T) {
require.True(t, !UnixNano(0).Before(UnixNano(0)))
require.True(t, !UnixNano(0).After(UnixNano(0)))
}

func TestUnixNanoTruncate(t *testing.T) {
now := time.Unix(31415926, 42)
t0 := ToUnixNano(now)

require.Equal(t, ToUnixNano(now.Truncate(1*time.Second)), t0.Truncate(1*time.Second))
require.Equal(t, ToUnixNano(now.Truncate(0)), t0.Truncate(0))
require.Equal(t, ToUnixNano(now.Truncate(-10000)), t0.Truncate(-10000))
}

0 comments on commit 1c1a7ad

Please sign in to comment.