From 14d466951baddadf44015bde2eda9ec796938251 Mon Sep 17 00:00:00 2001 From: Paul Dicker Date: Thu, 8 Jun 2023 09:41:37 +0200 Subject: [PATCH] Implement `AddAssign` and `SubAssign` --- src/duration.rs | 21 ++++++++++++++++++++- src/naive/time/mod.rs | 4 ++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/duration.rs b/src/duration.rs index add0333872..fb64591b80 100644 --- a/src/duration.rs +++ b/src/duration.rs @@ -10,7 +10,7 @@ //! Temporal quantification -use core::ops::{Add, Div, Mul, Neg, Sub}; +use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign}; use core::time::Duration as StdDuration; use core::{fmt, i64}; #[cfg(feature = "std")] @@ -384,6 +384,20 @@ impl Sub for Duration { } } +impl AddAssign for Duration { + fn add_assign(&mut self, rhs: Duration) { + let new = self.checked_add(&rhs).expect("`Duration + Duration` overflowed"); + *self = new; + } +} + +impl SubAssign for Duration { + fn sub_assign(&mut self, rhs: Duration) { + let new = self.checked_sub(&rhs).expect("`Duration - Duration` overflowed"); + *self = new; + } +} + impl Mul for Duration { type Output = Duration; @@ -533,6 +547,11 @@ mod tests { -(Duration::days(3) + Duration::seconds(70)), Duration::days(-4) + Duration::seconds(86_400 - 70) ); + + let mut d = Duration::default(); + d += Duration::minutes(1); + d -= Duration::seconds(30); + assert_eq!(d, Duration::seconds(30)); } #[test] diff --git a/src/naive/time/mod.rs b/src/naive/time/mod.rs index 4882bb69b0..965834ce95 100644 --- a/src/naive/time/mod.rs +++ b/src/naive/time/mod.rs @@ -590,11 +590,11 @@ impl NaiveTime { if frac >= 1_000_000_000 { let rfrac = 2_000_000_000 - frac; if rhs >= OldDuration::nanoseconds(i64::from(rfrac)) { - rhs = rhs - OldDuration::nanoseconds(i64::from(rfrac)); + rhs -= OldDuration::nanoseconds(i64::from(rfrac)); secs += 1; frac = 0; } else if rhs < OldDuration::nanoseconds(-i64::from(frac)) { - rhs = rhs + OldDuration::nanoseconds(i64::from(frac)); + rhs += OldDuration::nanoseconds(i64::from(frac)); frac = 0; } else { frac = (i64::from(frac) + rhs.num_nanoseconds().unwrap()) as u32;