Skip to content

time: clean up Instant overflow prevention#8128

Open
vilgotf wants to merge 1 commit into
tokio-rs:masterfrom
vilgotf:far-future
Open

time: clean up Instant overflow prevention#8128
vilgotf wants to merge 1 commit into
tokio-rs:masterfrom
vilgotf:far-future

Conversation

@vilgotf
Copy link
Copy Markdown
Contributor

@vilgotf vilgotf commented May 8, 2026

The Instant::far_future ctor unnecessarily called Instant::now (again). Shrinking Duration before calling Instant::add achieves the same result more succinctly.

Also fixed timeout_at using the wrong Location for its delay.

The `Instant::far_future` ctor unnecessarily called `Instant::now`
(again). Shrinking `Duration` before calling `Instant::add` achieves the
same result more succinctly.

Also fixed `timeout_at` using the wrong `Location` for its delay.
@Darksonn Darksonn added A-tokio Area: The main tokio crate M-time Module: tokio/time labels May 8, 2026
@ADD-SP ADD-SP self-requested a review May 8, 2026 17:59
@vilgotf
Copy link
Copy Markdown
Contributor Author

vilgotf commented May 10, 2026

Supersedes #7193

Comment thread tokio/src/time/sleep.rs
Comment on lines -126 to -129
match Instant::now().checked_add(duration) {
Some(deadline) => Sleep::new_timeout(deadline, location),
None => Sleep::new_timeout(Instant::far_future(), location),
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I would prefer to keep the checked_add() logic, to always perform the addition correctly when at all possible.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous code has no "correct" addition, even though it looks like it. This becomes clear when you inline Instant::far_future():

const SAFE_DELAY: Duration = Duration::from_secs(86400 * 365 * 30);
let deadline = Instant::now()
    .checked_add(duration)
    .unwrap_or_else(|| Instant::now().checked_add(SAFE_DELAY).unwrap());

This PR changes the above to:

const SAFE_DELAY: Duration = Duration::from_secs(86400 * 365 * 30);
let deadline = Instant::now().checked_add(duration.min(SAFE_DELAY)).unwrap();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-tokio Area: The main tokio crate M-time Module: tokio/time

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants