diff options
| author | Jacob Pratt <jacob@jhpratt.dev> | 2023-07-30 04:00:02 -0400 |
|---|---|---|
| committer | Jacob Pratt <jacob@jhpratt.dev> | 2023-07-30 04:00:02 -0400 |
| commit | f1d4e48c9c6409aff557b0117d48f2d7d1e05280 (patch) | |
| tree | d560a251248ec7ac587c166694af9ba5c0809847 | |
| parent | fb53384c94b87adebceb6048865c9fe305e71b92 (diff) | |
| download | rust-f1d4e48c9c6409aff557b0117d48f2d7d1e05280.tar.gz rust-f1d4e48c9c6409aff557b0117d48f2d7d1e05280.zip | |
Fix implementation of `Duration::checked_div`
| -rw-r--r-- | library/core/src/time.rs | 8 | ||||
| -rw-r--r-- | library/core/tests/time.rs | 1 |
2 files changed, 5 insertions, 4 deletions
diff --git a/library/core/src/time.rs b/library/core/src/time.rs index b08d5782ab6..1e8d28979e6 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -656,10 +656,10 @@ impl Duration { #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")] pub const fn checked_div(self, rhs: u32) -> Option<Duration> { if rhs != 0 { - let secs = self.secs / (rhs as u64); - let carry = self.secs - secs * (rhs as u64); - let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64); - let nanos = self.nanos.0 / rhs + (extra_nanos as u32); + let (secs, extra_secs) = (self.secs / (rhs as u64), self.secs % (rhs as u64)); + let (mut nanos, extra_nanos) = (self.nanos.0 / rhs, self.nanos.0 % rhs); + nanos += + ((extra_secs * (NANOS_PER_SEC as u64) + extra_nanos as u64) / (rhs as u64)) as u32; debug_assert!(nanos < NANOS_PER_SEC); Some(Duration::new(secs, nanos)) } else { diff --git a/library/core/tests/time.rs b/library/core/tests/time.rs index 872611937cc..bd6e63edbb9 100644 --- a/library/core/tests/time.rs +++ b/library/core/tests/time.rs @@ -170,6 +170,7 @@ fn saturating_mul() { fn div() { assert_eq!(Duration::new(0, 1) / 2, Duration::new(0, 0)); assert_eq!(Duration::new(1, 1) / 3, Duration::new(0, 333_333_333)); + assert_eq!(Duration::new(1, 1) / 7, Duration::new(0, 142_857_143)); assert_eq!(Duration::new(99, 999_999_000) / 100, Duration::new(0, 999_999_990)); } |
