Merge pull request #125 from xoviat/timeout

add with_timeout
This commit is contained in:
xoviat 2021-03-29 15:56:51 -05:00 committed by GitHub
commit 7094c4e619
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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::pin::Pin;
use core::task::{Context, Poll};
use futures::Stream;
use futures::{future::select, future::Either, pin_mut, Stream};
use super::raw;
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).
pub struct Timer {
expires_at: Instant,

View File

@ -5,7 +5,7 @@ mod duration;
mod instant;
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 instant::Instant;
pub use traits::*;