From 9cf04b5a22e20fd0a537196a610b0e2b85b8d485 Mon Sep 17 00:00:00 2001 From: tiif Date: Sat, 8 Jun 2024 00:56:48 +0800 Subject: [PATCH] Use modulo operation to convert nanosecond to Duration --- src/tools/miri/src/clock.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/tools/miri/src/clock.rs b/src/tools/miri/src/clock.rs index da2c54745a03..942593530c37 100644 --- a/src/tools/miri/src/clock.rs +++ b/src/tools/miri/src/clock.rs @@ -39,13 +39,14 @@ impl Instant { InstantKind::Virtual { nanoseconds }, InstantKind::Virtual { nanoseconds: earlier }, ) => { - // If it exceeded u64::MAX nanosecond, we will just keep u64::MAX nanosecond, - // Duration can't take in more than u64::MAX. - let duration = match u64::try_from(nanoseconds.saturating_sub(earlier)) { - Ok(nanosecond) => Duration::from_nanos(nanosecond), - Err(_err) => Duration::from_nanos(u64::MAX), - }; - Duration::new(duration.as_secs(), duration.subsec_nanos()) + // It is possible for second to overflow because u64::MAX < (u128::MAX / 1e9). + let seconds = u64::try_from( + nanoseconds.saturating_sub(earlier).saturating_div(1_000_000_000), + ) + .unwrap(); + // It is impossible for nanosecond to overflow because u32::MAX > 1e9. + let nanosecond = u32::try_from(nanoseconds.wrapping_rem(1_000_000_000)).unwrap(); + Duration::new(seconds, nanosecond) } _ => panic!("all `Instant` must be of the same kind"), }