Merge pull request #3079 from aurelj/with_timeout

implement with_timeout()/with_deadline() method style call on Future
This commit is contained in:
Ulf Lilleengen 2024-06-22 14:14:35 +00:00 committed by GitHub
commit 95d0cae897
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 1 deletions

View File

@ -32,7 +32,7 @@ pub use delay::{block_for, Delay};
pub use duration::Duration;
pub use embassy_time_driver::TICK_HZ;
pub use instant::Instant;
pub use timer::{with_deadline, with_timeout, Ticker, TimeoutError, Timer};
pub use timer::{with_deadline, with_timeout, Ticker, TimeoutError, Timer, WithTimeout};
const fn gcd(a: u64, b: u64) -> u64 {
if b == 0 {

View File

@ -37,6 +37,36 @@ pub async fn with_deadline<F: Future>(at: Instant, fut: F) -> Result<F::Output,
}
}
/// Provides functions to run a given future with a timeout or a deadline.
pub trait WithTimeout {
/// Output type of the future.
type Output;
/// Runs a given future with a timeout.
///
/// If the future completes before the timeout, its output is returned. Otherwise, on timeout,
/// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
async fn with_timeout(self, timeout: Duration) -> Result<Self::Output, TimeoutError>;
/// Runs a given future with a deadline time.
///
/// If the future completes before the deadline, its output is returned. Otherwise, on timeout,
/// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned.
async fn with_deadline(self, at: Instant) -> Result<Self::Output, TimeoutError>;
}
impl<F: Future> WithTimeout for F {
type Output = F::Output;
async fn with_timeout(self, timeout: Duration) -> Result<Self::Output, TimeoutError> {
with_timeout(timeout, self).await
}
async fn with_deadline(self, at: Instant) -> Result<Self::Output, TimeoutError> {
with_deadline(at, self).await
}
}
/// A future that completes at a specified [Instant](struct.Instant.html).
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Timer {