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 the once_future() combinator #59

Merged
merged 6 commits into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 2 additions & 0 deletions src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ use core::fmt;
use core::marker::PhantomData;
use core::pin::Pin;

use futures_core::Stream;

notgull marked this conversation as resolved.
Show resolved Hide resolved
use pin_project_lite::pin_project;

#[cfg(feature = "std")]
Expand Down
47 changes: 47 additions & 0 deletions src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,53 @@ where
}
}

/// Creates a stream that invokes the given future as its first item, and then
/// produces no more items.
///
/// # Example
///
/// ```
/// use futures_lite::{stream, prelude::*};
///
/// # spin_on::spin_on(async {
/// let mut stream = Box::pin(stream::once_future(async { 1 }));
/// assert_eq!(stream.next().await, Some(1));
/// assert_eq!(stream.next().await, None);
/// # });
/// ```
pub fn once_future<F: Future>(future: F) -> OnceFuture<F> {
OnceFuture {
future: Some(future),
}
}

pin_project! {
/// Stream for the [`once_future()`] method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct OnceFuture<F> {
#[pin]
future: Option<F>,
}
}

impl<F: Future> Stream for OnceFuture<F> {
type Item = F::Output;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();

match this.future.as_mut().as_pin_mut().map(|f| f.poll(cx)) {
Some(Poll::Ready(t)) => {
this.future.set(None);
Poll::Ready(Some(t))
}
Some(Poll::Pending) => Poll::Pending,
None => Poll::Ready(None),
}
}
}

/// Extension trait for [`Stream`].
pub trait StreamExt: Stream {
/// A convenience for calling [`Stream::poll_next()`] on `!`[`Unpin`] types.
Expand Down