Add timeout
This commit is contained in:
parent
e8f6bc46f7
commit
3f8615aab7
|
@ -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");
|
||||
|
||||
|
|
32
src/time.rs
32
src/time.rs
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue