Skip to content

fix: lossy truncation in checked Instant arithmetic #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions src/instant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,14 +171,16 @@ impl Instant {
/// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
/// otherwise.
pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
self.0.checked_add(duration.as_nanos() as u64).map(Instant)
let total_nanos = u64::try_from(duration.as_nanos()).ok()?;
self.0.checked_add(total_nanos).map(Instant)
}

/// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
/// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
/// otherwise.
pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.0.checked_sub(duration.as_nanos() as u64).map(Instant)
let total_nanos = u64::try_from(duration.as_nanos()).ok()?;
self.0.checked_sub(total_nanos).map(Instant)
}
}

Expand Down Expand Up @@ -371,4 +373,27 @@ mod tests {
assert_eq!(t4.0, 1440);
})
}

// Test fix for issue #109
#[test]
fn checked_arithmetic_u64_overflow() {
fn nanos_to_dur(total_nanos: u128) -> Duration {
let nanos_per_sec = Duration::from_secs(1).as_nanos();
let secs = total_nanos / nanos_per_sec;
let nanos = total_nanos % nanos_per_sec;
let dur = Duration::new(secs as _, nanos as _);
assert_eq!(dur.as_nanos(), total_nanos);
dur
}

let dur = nanos_to_dur(1 << 64);
let now = Instant::now();

let behind = now.checked_sub(dur);
let ahead = now.checked_add(dur);

assert_ne!(Duration::ZERO, dur);
assert_ne!(Some(now), behind);
assert_ne!(Some(now), ahead);
}
}
Loading