Skip to content

Commit

Permalink
Merge pull request #323 from cardigan1008/issue-244-14
Browse files Browse the repository at this point in the history
Fix ceil with zero duration
  • Loading branch information
ChristopherRabotin authored Jul 28, 2024
2 parents 58df214 + c58ca0b commit 754a86e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/duration/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,9 +538,11 @@ impl Duration {
/// assert_eq!(two_hours_three_min.floor(1.hours() + 5.minutes()), 1.hours() + 5.minutes());
/// ```
pub fn floor(&self, duration: Self) -> Self {
Self::from_total_nanoseconds(
self.total_nanoseconds() - self.total_nanoseconds() % duration.total_nanoseconds(),
)
Self::from_total_nanoseconds(if duration.total_nanoseconds() == 0 {
0
} else {
self.total_nanoseconds() - self.total_nanoseconds() % duration.total_nanoseconds()
})
}

/// Ceils this duration to the closest provided duration
Expand Down
12 changes: 12 additions & 0 deletions tests/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,3 +577,15 @@ fn test_min_max() {
assert_eq!(d1, d1.max(d0));
assert_eq!(d1, d0.max(d1));
}

#[test]
fn regression_test_gh_244() {
let zero = Duration::ZERO;
// Test that the ceil of a zero duration is still zero.
assert_eq!(zero.ceil(zero), zero);
let non_zero = Duration::from_parts(1, 23456);
// Test that the ceil of a non-zero duration by zero is still zero.
assert_eq!(non_zero.ceil(zero), zero);
// Test that the ceil of a zero duration by a non-zero is non-zero duration.
assert_eq!(zero.ceil(non_zero), non_zero);
}

0 comments on commit 754a86e

Please sign in to comment.