Skip to content

Manually implement the future for with_timeout #4123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 42 additions & 19 deletions embassy-time/src/timer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use core::future::{poll_fn, Future};
use core::pin::{pin, Pin};
use core::pin::Pin;
use core::task::{Context, Poll};

use futures_util::future::{select, Either};
use futures_util::stream::FusedStream;
use futures_util::Stream;

Expand All @@ -17,53 +16,77 @@ pub struct TimeoutError;
///
/// 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.
pub async fn with_timeout<F: Future>(timeout: Duration, fut: F) -> Result<F::Output, TimeoutError> {
let timeout_fut = Timer::after(timeout);
match select(pin!(fut), timeout_fut).await {
Either::Left((r, _)) => Ok(r),
Either::Right(_) => Err(TimeoutError),
pub fn with_timeout<F: Future>(timeout: Duration, fut: F) -> TimeoutFuture<F> {
TimeoutFuture {
timer: Timer::after(timeout),
fut,
}
}

/// 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.
pub async fn with_deadline<F: Future>(at: Instant, fut: F) -> Result<F::Output, TimeoutError> {
let timeout_fut = Timer::at(at);
match select(pin!(fut), timeout_fut).await {
Either::Left((r, _)) => Ok(r),
Either::Right(_) => Err(TimeoutError),
pub fn with_deadline<F: Future>(at: Instant, fut: F) -> TimeoutFuture<F> {
TimeoutFuture {
timer: Timer::at(at),
fut,
}
}

/// Provides functions to run a given future with a timeout or a deadline.
pub trait WithTimeout {
pub trait WithTimeout: Sized {
/// 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>;
fn with_timeout(self, timeout: Duration) -> TimeoutFuture<Self>;

/// 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>;
fn with_deadline(self, at: Instant) -> TimeoutFuture<Self>;
}

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
fn with_timeout(self, timeout: Duration) -> TimeoutFuture<Self> {
with_timeout(timeout, self)
}

async fn with_deadline(self, at: Instant) -> Result<Self::Output, TimeoutError> {
with_deadline(at, self).await
fn with_deadline(self, at: Instant) -> TimeoutFuture<Self> {
with_deadline(at, self)
}
}

/// Future for the [`with_timeout`] and [`with_deadline`] functions.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct TimeoutFuture<F> {
timer: Timer,
fut: F,
}

impl<F: Unpin> Unpin for TimeoutFuture<F> {}

impl<F: Future> Future for TimeoutFuture<F> {
type Output = Result<F::Output, TimeoutError>;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = unsafe { self.get_unchecked_mut() };
let fut = unsafe { Pin::new_unchecked(&mut this.fut) };
let timer = unsafe { Pin::new_unchecked(&mut this.timer) };
if let Poll::Ready(x) = fut.poll(cx) {
return Poll::Ready(Ok(x));
}
if let Poll::Ready(_) = timer.poll(cx) {
return Poll::Ready(Err(TimeoutError));
}
Poll::Pending
}
}

Expand Down