-
Notifications
You must be signed in to change notification settings - Fork 339
Add future::timeout() #20
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 all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
use std::error::Error; | ||
use std::fmt; | ||
use std::pin::Pin; | ||
use std::time::Duration; | ||
|
||
use futures_timer::Delay; | ||
|
||
use crate::future::Future; | ||
use crate::task::{Context, Poll}; | ||
|
||
/// Awaits a future or times out after a duration of time. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async { | ||
/// # | ||
/// use std::time::Duration; | ||
/// | ||
/// use async_std::future; | ||
/// | ||
/// let never = future::pending::<()>(); | ||
/// let dur = Duration::from_millis(5); | ||
/// assert!(future::timeout(dur, never).await.is_err()); | ||
/// # | ||
/// # Ok(()) }) } | ||
/// ``` | ||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))] | ||
pub async fn timeout<F, T>(dur: Duration, f: F) -> Result<T, TimeoutError> | ||
where | ||
F: Future<Output = T>, | ||
{ | ||
let f = TimeoutFuture { | ||
future: f, | ||
delay: Delay::new(dur), | ||
}; | ||
f.await | ||
} | ||
|
||
/// A future that times out after a duration of time. | ||
#[doc(hidden)] | ||
#[allow(missing_debug_implementations)] | ||
struct TimeoutFuture<F> { | ||
future: F, | ||
delay: Delay, | ||
} | ||
|
||
impl<F> TimeoutFuture<F> { | ||
pin_utils::unsafe_pinned!(future: F); | ||
pin_utils::unsafe_pinned!(delay: Delay); | ||
} | ||
|
||
impl<F: Future> Future for TimeoutFuture<F> { | ||
type Output = Result<F::Output, TimeoutError>; | ||
|
||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
match self.as_mut().future().poll(cx) { | ||
Poll::Ready(v) => Poll::Ready(Ok(v)), | ||
Poll::Pending => match self.delay().poll(cx) { | ||
Poll::Ready(_) => Poll::Ready(Err(TimeoutError { _priv: () })), | ||
Poll::Pending => Poll::Pending, | ||
}, | ||
} | ||
} | ||
} | ||
|
||
/// An error returned when a future times out. | ||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))] | ||
#[derive(Clone, Copy, Debug, Eq, PartialEq)] | ||
pub struct TimeoutError { | ||
_priv: (), | ||
} | ||
|
||
impl Error for TimeoutError {} | ||
|
||
impl fmt::Display for TimeoutError { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
"future has timed out".fmt(f) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does it mean that in case of a CPU-bound future that is blocking the current thread you will never try to poll the timer and return TimeoutError?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
/cc @stjepang
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kpp That's a good point - do you think we should check for timeout before polling the future?
I worry a bit that this would add overhead to futures that are quick to poll or immediately ready. And if the future is CPU-bound and takes a really long time, we can still get stuck if the timeout occurs while that future is running.
All things considered, I think I prefer the current behavior. Wdyt?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep... I don't see a better solution for this.
Still I would rewrite the current implementation as
f.select(Delay::new(dur))...
;)