add with_timeout

This commit is contained in:
xoviat 2021-03-29 15:48:57 -05:00
parent 86f59d1444
commit 49d87ac868
2 changed files with 12 additions and 2 deletions

View file

@ -2,7 +2,7 @@ use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::pin::Pin; use core::pin::Pin;
use core::task::{Context, Poll}; use core::task::{Context, Poll};
use futures::Stream; use futures::{future::select, future::Either, pin_mut, Stream};
use super::raw; use super::raw;
use crate::time::{Duration, Instant}; use crate::time::{Duration, Instant};
@ -31,6 +31,16 @@ impl crate::traits::delay::Delay for Delay {
} }
} }
pub struct TimeoutError;
pub async fn with_timeout<F: Future>(timeout: Duration, fut: F) -> Result<F::Output, TimeoutError> {
let timeout_fut = Timer::after(timeout);
pin_mut!(fut);
match select(fut, timeout_fut).await {
Either::Left((r, _)) => Ok(r),
Either::Right(_) => Err(TimeoutError),
}
}
/// A future that completes at a specified [Instant](struct.Instant.html). /// A future that completes at a specified [Instant](struct.Instant.html).
pub struct Timer { pub struct Timer {
expires_at: Instant, expires_at: Instant,

View file

@ -5,7 +5,7 @@ mod duration;
mod instant; mod instant;
mod traits; mod traits;
pub use crate::executor::timer::{Delay, Ticker, Timer}; pub use crate::executor::timer::{with_timeout, Delay, Ticker, TimeoutError, Timer};
pub use duration::Duration; pub use duration::Duration;
pub use instant::Instant; pub use instant::Instant;
pub use traits::*; pub use traits::*;