Skip to content

Commit

Permalink
Implement AddAssign and SubAssign
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Jun 8, 2023
1 parent 965ab29 commit f34af09
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
21 changes: 20 additions & 1 deletion src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(any(feature = "std", test))]
Expand Down Expand Up @@ -380,6 +380,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<i32> for Duration {
type Output = Duration;

Expand Down Expand Up @@ -534,6 +548,11 @@ mod tests {
-(Duration::days(3) + Duration::seconds(70)),
Duration::days(-4) + Duration::seconds(86400 - 70)
);

let mut d = Duration::default();
d += Duration::minutes(1);
d -= Duration::seconds(30);
assert_eq!(d, Duration::seconds(30));
}

#[test]
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 @@ -536,11 +536,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;
Expand Down

0 comments on commit f34af09

Please sign in to comment.