Use modulo operation to convert nanosecond to Duration

This commit is contained in:
tiif 2024-06-08 00:56:48 +08:00
parent 9f60709ffd
commit 9cf04b5a22

View File

@ -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"),
}