Skip to content
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

add Fuse support to FutureExt #101

Merged
merged 5 commits into from
May 11, 2024
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
60 changes: 60 additions & 0 deletions src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,66 @@ where
}
}

/// Fuse a future such that `poll` will never again be called once it has
/// completed. This method can be used to turn any `Future` into a
/// `FusedFuture`.
///
/// Normally, once a future has returned `Poll::Ready` from `poll`,
/// any further calls could exhibit bad behavior such as blocking
/// forever, panicking, never returning, etc. If it is known that `poll`
/// may be called too often then this method can be used to ensure that it
/// has defined semantics.
///
/// If a `fuse`d future is `poll`ed after having returned `Poll::Ready`
/// previously, it will return `Poll::Pending`, from `poll` again (and will
/// continue to do so for all future calls to `poll`).
///
/// This combinator will drop the underlying future as soon as it has been
/// completed to ensure resources are reclaimed as soon as possible.
pub fn fuse<F>(future: F) -> Fuse<F>
where
F: Future + Sized,
{
Fuse::new(future)
}

pin_project! {
/// [`Future`] for the [`fuse`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Fuse<Fut> {
#[pin]
inner: Option<Fut>,
}
}

impl<Fut> Fuse<Fut> {
fn new(f: Fut) -> Self {
Self { inner: Some(f) }
}
}

impl<Fut: Future> Future for Fuse<Fut> {
type Output = Fut::Output;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Fut::Output> {
match self
.as_mut()
.project()
.inner
.as_pin_mut()
.map(|f| f.poll(cx))
{
Some(Poll::Ready(output)) => {
self.project().inner.set(None);
Poll::Ready(output)
}

Some(Poll::Pending) | None => Poll::Pending,
}
}
}

/// Returns the result of the future that completes first, with no preference if both are ready.
///
/// Each time [`Race`] is polled, the two inner futures are polled in random order. Therefore, no
Expand Down
Loading