async_tick/
timeout.rs

1use super::sleep::*;
2use core::future::Future;
3use core::pin::Pin;
4use core::task::{Context, Poll};
5use core::time::Duration;
6
7pub fn timeout<T: Future + Unpin>(duration: Duration, future: T) -> Timeout<T> {
8    let sleep = sleep(duration);
9    Timeout { future, sleep }
10}
11
12pub struct Timeout<T: Future + Unpin> {
13    future: T,
14    sleep: Sleep,
15}
16impl<T: Future + Unpin> Future for Timeout<T> {
17    type Output = Result<T::Output, ()>;
18    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
19        // First, try polling the future
20        if let Poll::Ready(v) = Pin::new(&mut self.future).poll(cx) {
21            return Poll::Ready(Ok(v));
22        }
23
24        // Now check the timer
25        match Pin::new(&mut self.sleep).poll(cx) {
26            Poll::Ready(()) => Poll::Ready(Err(())),
27            Poll::Pending => Poll::Pending,
28        }
29    }
30}