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
11pub 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 #[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}