Skip to content

Commit

Permalink
clock: Fix Add negative duration
Browse files Browse the repository at this point in the history
  • Loading branch information
sunshineplan committed Jan 16, 2024
1 parent 39d4144 commit 955867b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
6 changes: 3 additions & 3 deletions clock/clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ type Clock struct {
wall uint64
}

func abs[Int int | uint64](wall Int) uint64 {
func abs[Int int | float64 | uint64](wall Int) uint64 {
for wall < 0 {
wall += secondsPerDay
}
return uint64(wall % secondsPerDay)
return uint64(int64(wall) % secondsPerDay)
}

func New(hour, min, sec int) Clock {
Expand Down Expand Up @@ -134,7 +134,7 @@ func (c Clock) Compare(u Clock) int {
}

func (c Clock) Add(d time.Duration) Clock {
return Clock{abs(c.wall + uint64(d.Seconds()))}
return Clock{abs(float64(c.wall) + d.Seconds())}
}

func (c Clock) Sub(u Clock) time.Duration {
Expand Down
18 changes: 17 additions & 1 deletion clock/clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,22 @@ func TestSeconds(t *testing.T) {
}
}

func TestAdd(t *testing.T) {
for i, tc := range []struct {
c Clock
d time.Duration
u Clock
}{
{Clock{}, 0, Clock{}},
{Clock{}, time.Second, New(0, 0, 1)},
{New(0, 0, 1), -time.Second, Clock{}},
} {
if got := tc.c.Add(tc.d); got != tc.u {
t.Errorf("#%d: got %s; want %s", i, got, tc.u)
}
}
}

func TestSub(t *testing.T) {
for i, tc := range []struct {
c Clock
Expand All @@ -88,7 +104,7 @@ func TestSub(t *testing.T) {
{New(12, 0, 0), New(12, 30, 0), -30 * time.Minute},
} {
if got := tc.c.Sub(tc.u); got != tc.d {
t.Errorf("#%d: Sub(%v, %v): got %v; want %v", i, tc.c, tc.u, got, tc.d)
t.Errorf("#%d: got %v; want %v", i, got, tc.d)
}
}
}
Expand Down

0 comments on commit 955867b

Please sign in to comment.