Make NaiveTime::overflowing_sub_signed const

This commit is contained in:
Paul Dicker 2023-10-02 13:17:55 +02:00 committed by Paul Dicker
parent e56f9c5797
commit f78eb20ef1
2 changed files with 16 additions and 7 deletions

View File

@ -435,6 +435,15 @@ 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 {
@ -442,11 +451,11 @@ impl Neg for 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 }
}
}

View File

@ -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)
}