Skip to content

Commit

Permalink
Make NaiveTime::overflowing_sub_signed const
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Jan 30, 2024
1 parent f0c55f7 commit ebad385
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
19 changes: 14 additions & 5 deletions src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,18 +350,27 @@ impl Duration {
}
Ok(StdDuration::new(self.secs as u64, self.nanos as u32))
}

/// This duplicates `Neg::neg` because trait methods can't be const yet.
pub(crate) const fn neg(self) -> Duration {
let (secs_diff, nanos) = match self.nanos {
0 => (0, 0),
nanos => (1, NANOS_PER_SEC - nanos),
};
Duration { secs: -self.secs - secs_diff, nanos }
}
}

impl Neg for Duration {
type Output = Duration;

#[inline]
fn neg(self) -> Duration {
if self.nanos == 0 {
Duration { secs: -self.secs, nanos: 0 }
} else {
Duration { secs: -self.secs - 1, nanos: NANOS_PER_SEC - self.nanos }
}
let (secs_diff, nanos) = match self.nanos {
0 => (0, 0),
nanos => (1, NANOS_PER_SEC - nanos),
};
Duration { secs: -self.secs - secs_diff, nanos }
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/naive/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -639,8 +639,8 @@ impl NaiveTime {
/// ```
#[inline]
#[must_use]
pub fn overflowing_sub_signed(&self, rhs: OldDuration) -> (NaiveTime, i64) {
let (time, rhs) = self.overflowing_add_signed(-rhs);
pub const fn overflowing_sub_signed(&self, rhs: OldDuration) -> (NaiveTime, i64) {
let (time, rhs) = self.overflowing_add_signed(rhs.neg());
(time, -rhs) // safe to negate, rhs is within +/- (2^63 / 1000)
}

Expand Down

0 comments on commit ebad385

Please sign in to comment.