Add timeout

This commit is contained in:
Aode (lion) 2022-03-05 17:13:11 -06:00
parent e8f6bc46f7
commit 3f8615aab7
2 changed files with 33 additions and 1 deletions

View file

@ -7,7 +7,7 @@ async fn echo_to(port: u16) -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect(sockaddr)?;
stream.set_nonblocking(true)?;
let mut stream = Async::new(stream);
let mut stream = Async::new(stream)?;
println!("Connected");

View file

@ -20,6 +20,18 @@ pub fn interval_at(instant: Instant, duration: Duration) -> Interval {
}
}
pub fn timeout<F: std::future::Future + Unpin>(duration: Duration, future: F) -> Timeout<F> {
Timeout {
timer: Timer::new(duration),
future,
}
}
pub struct Timeout<F> {
timer: Timer,
future: F,
}
pub struct Interval {
next: Instant,
duration: Duration,
@ -46,3 +58,23 @@ impl Interval {
Timer::new(duration)
}
}
impl<F> std::future::Future for Timeout<F>
where
F: std::future::Future + Unpin,
{
type Output = std::io::Result<F::Output>;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
let this = self.get_mut();
if std::pin::Pin::new(&mut this.timer).poll(cx).is_ready() {
return std::task::Poll::Ready(Err(std::io::ErrorKind::TimedOut.into()));
}
std::pin::Pin::new(&mut this.future).poll(cx).map(Ok)
}
}