Skip to content

Commit

Permalink
Use checked_add and checked_sub in Add and Sub impls
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Jun 8, 2023
1 parent e1cb286 commit 965ab29
Showing 1 changed file with 2 additions and 14 deletions.
16 changes: 2 additions & 14 deletions src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,27 +368,15 @@ impl Add for Duration {
type Output = Duration;

fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs + rhs.secs;
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs += 1;
}
Duration { secs, nanos }
self.checked_add(&rhs).expect("`Duration + Duration` overflowed")
}
}

impl Sub for Duration {
type Output = Duration;

fn sub(self, rhs: Duration) -> Duration {
let mut secs = self.secs - rhs.secs;
let mut nanos = self.nanos - rhs.nanos;
if nanos < 0 {
nanos += NANOS_PER_SEC;
secs -= 1;
}
Duration { secs, nanos }
self.checked_sub(&rhs).expect("`Duration - Duration` overflowed")
}
}

Expand Down

0 comments on commit 965ab29

Please sign in to comment.