Skip to content
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

Handle potential overflow gracefully #68

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "futures-timer"
version = "3.0.2"
version = "3.0.3"
authors = ["Alex Crichton <[email protected]>"]
edition = "2018"
license = "MIT/Apache-2.0"
Expand Down
28 changes: 26 additions & 2 deletions src/native/delay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ impl Delay {
/// The default timer will be spun up in a helper thread on first use.
#[inline]
pub fn new(dur: Duration) -> Delay {
Delay::new_handle(Instant::now() + dur, Default::default())
Delay::new_handle(
Instant::now()
.checked_add(dur)
.unwrap_or_else(Self::max_instant),
Default::default(),
)
}

/// Creates a new future which will fire at the time specified by `at`.
Expand Down Expand Up @@ -74,6 +79,21 @@ impl Delay {
}
}

fn max_instant() -> Instant {
let mut max = Instant::now();
let mut duration = Duration::MAX;

while duration > Duration::ZERO {
if let Some(new_max) = max.checked_add(duration) {
max = new_max;
} else {
duration /= 2;
}
}

max
}

fn _reset(&mut self, dur: Duration) -> Result<(), ()> {
let state = match self.state {
Some(ref state) => state,
Expand All @@ -92,7 +112,11 @@ impl Delay {
Err(s) => bits = s,
}
}
*state.at.lock().unwrap() = Some(Instant::now() + dur);
*state.at.lock().unwrap() = Some(
Instant::now()
.checked_add(dur)
.unwrap_or_else(Self::max_instant),
);
// If we fail to push our node then we've become an inert timer, so
// we'll want to clear our `state` field accordingly
timeouts.list.push(state)?;
Expand Down
7 changes: 7 additions & 0 deletions tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,10 @@ async fn reset() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
assert!(i.elapsed() > dur);
Ok(())
}

#[test]
fn overflow() {
// Could have overflown if wasn't implemented correctly
let mut delay = Delay::new(Duration::MAX);
delay.reset(Duration::MAX);
}