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