Skip to content

Commit

Permalink
Fix saturating behavior of Duration::abs
Browse files Browse the repository at this point in the history
Previously, the nanoseconds value would have been incorrect if the
seconds field was saturated.
  • Loading branch information
jhpratt committed Jun 11, 2023
1 parent 976a20c commit 0e99ae7
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
1 change: 1 addition & 0 deletions tests/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ fn abs() {
assert_eq!(1.seconds().abs(), 1.seconds());
assert_eq!(0.seconds().abs(), 0.seconds());
assert_eq!((-1).seconds().abs(), 1.seconds());
assert_eq!(Duration::new(i64::MIN, 0).abs(), Duration::MAX);
}

#[test]
Expand Down
5 changes: 4 additions & 1 deletion time/src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,10 @@ impl Duration {
/// assert_eq!((-1).seconds().abs(), 1.seconds());
/// ```
pub const fn abs(self) -> Self {
Self::new_unchecked(self.seconds.saturating_abs(), self.nanoseconds.abs())
match self.seconds.checked_abs() {
Some(seconds) => Self::new_unchecked(seconds, self.nanoseconds.abs()),
None => Self::MAX,
}
}

/// Convert the existing `Duration` to a `std::time::Duration` and its sign. This returns a
Expand Down

0 comments on commit 0e99ae7

Please sign in to comment.