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 Sep 29, 2023
1 parent a2820c4 commit bd6573a
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 @@ -372,27 +372,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 bd6573a

Please sign in to comment.