async_std/io/
timeout.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use std::time::Duration;
5
6use pin_project_lite::pin_project;
7
8use crate::io;
9use crate::utils::{timer_after, Timer};
10
11/// Awaits an I/O future or times out after a duration of time.
12///
13/// If you want to await a non I/O future consider using
14/// [`future::timeout`](../future/fn.timeout.html) instead.
15///
16/// # Examples
17///
18/// ```no_run
19/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
20/// #
21/// use std::time::Duration;
22///
23/// use async_std::io;
24///
25/// io::timeout(Duration::from_secs(5), async {
26///     let stdin = io::stdin();
27///     let mut line = String::new();
28///     let n = stdin.read_line(&mut line).await?;
29///     Ok(())
30/// })
31/// .await?;
32/// #
33/// # Ok(()) }) }
34/// ```
35pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
36where
37    F: Future<Output = io::Result<T>>,
38{
39    Timeout {
40        timeout: timer_after(dur),
41        future: f,
42    }
43    .await
44}
45
46pin_project! {
47    /// Future returned by the `FutureExt::timeout` method.
48    #[derive(Debug)]
49    pub struct Timeout<F, T>
50    where
51        F: Future<Output = io::Result<T>>,
52    {
53        #[pin]
54        future: F,
55        #[pin]
56        timeout: Timer,
57    }
58}
59
60impl<F, T> Future for Timeout<F, T>
61where
62    F: Future<Output = io::Result<T>>,
63{
64    type Output = io::Result<T>;
65
66    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
67        let this = self.project();
68        match this.future.poll(cx) {
69            Poll::Pending => {}
70            other => return other,
71        }
72
73        if this.timeout.poll(cx).is_ready() {
74            let err = Err(io::Error::new(io::ErrorKind::TimedOut, "future timed out"));
75            Poll::Ready(err)
76        } else {
77            Poll::Pending
78        }
79    }
80}