Skip to content

Commit 9cf04b5

Browse files
committed
Use modulo operation to convert nanosecond to Duration
1 parent 9f60709 commit 9cf04b5

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/tools/miri/src/clock.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,14 @@ impl Instant {
3939
InstantKind::Virtual { nanoseconds },
4040
InstantKind::Virtual { nanoseconds: earlier },
4141
) => {
42-
// If it exceeded u64::MAX nanosecond, we will just keep u64::MAX nanosecond,
43-
// Duration can't take in more than u64::MAX.
44-
let duration = match u64::try_from(nanoseconds.saturating_sub(earlier)) {
45-
Ok(nanosecond) => Duration::from_nanos(nanosecond),
46-
Err(_err) => Duration::from_nanos(u64::MAX),
47-
};
48-
Duration::new(duration.as_secs(), duration.subsec_nanos())
42+
// It is possible for second to overflow because u64::MAX < (u128::MAX / 1e9).
43+
let seconds = u64::try_from(
44+
nanoseconds.saturating_sub(earlier).saturating_div(1_000_000_000),
45+
)
46+
.unwrap();
47+
// It is impossible for nanosecond to overflow because u32::MAX > 1e9.
48+
let nanosecond = u32::try_from(nanoseconds.wrapping_rem(1_000_000_000)).unwrap();
49+
Duration::new(seconds, nanosecond)
4950
}
5051
_ => panic!("all `Instant` must be of the same kind"),
5152
}

0 commit comments

Comments
 (0)