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

feat: add StreamExt::take_until. #103

Merged
merged 6 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Version 2.4.0
LebranceBW marked this conversation as resolved.
Show resolved Hide resolved

- Add `StreamExt::take_until` for taking elements from the stream until the provided futures resolved (#99).

# Version 2.3.0

- Add `StreamExt::drain` for draining objects from a `Stream` without waiting (#70).
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "futures-lite"
# When publishing a new version:
# - Update CHANGELOG.md
# - Create "v2.x.y" git tag
version = "2.3.0"
version = "2.4.0"
authors = [
"Stjepan Glavina <[email protected]>",
"Contributors to futures-rs",
Expand Down
167 changes: 167 additions & 0 deletions src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,52 @@ pub trait StreamExt: Stream {
}
}

/// Take elements from this stream until the provided future resolves.
///
/// This function will take elements from the stream until the provided
/// stopping future `fut` resolves. Once the `fut` future becomes ready,
/// this stream combinator will always return that the stream is done.
///
/// The stopping future may return any type. Once the stream is stopped
/// the result of the stopping future may be accessed with `TakeUntil::take_result()`.
/// The stream may also be resumed with `TakeUntil::take_future()`.
/// See the documentation of [`TakeUntil`] for more information.
///
/// ```
/// use futures_lite::stream::{self, StreamExt};
/// use futures_lite::future;
/// use std::task::Poll;
///
/// let stream = stream::iter(1..=10);
///
/// # spin_on::spin_on(async {
/// let mut i = 0;
/// let stop_fut = future::poll_fn(|_cx| {
/// i += 1;
/// if i <= 5 {
/// Poll::Pending
/// } else {
/// Poll::Ready(())
/// }
/// });
///
/// let stream = stream.take_until(stop_fut);
///
/// assert_eq!(vec![1, 2, 3, 4, 5], stream.collect::<Vec<_>>().await);
/// # });
fn take_until<F>(self, future: F) -> TakeUntil<Self, F>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer this as a free function, rather than a member of the trait.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will move it out of this trait, but I'd remind you that futures library take it as a member of StreamExt

where
Self: Sized,
F: Future,
{
TakeUntil {
stream: self,
fut: future.into(),
LebranceBW marked this conversation as resolved.
Show resolved Hide resolved
fut_result: None,
free: false,
}
}

/// Skips the first `n` items of the stream.
///
/// # Examples
Expand Down Expand Up @@ -2620,6 +2666,127 @@ where
}
}

pin_project! {
/// Stream for the [`StreamExt::take_until()`] method.
#[derive(Clone, Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct TakeUntil<S: Stream, Fut: Future> {
#[pin]
stream: S,
// Contains the inner Future on start and None once the inner Future is resolved
// or taken out by the user.
#[pin]
fut: Option<Fut>,
// Contains fut's return value once fut is resolved
fut_result: Option<Fut::Output>,
// Whether the future was taken out by the user.
free: bool,
}
}

impl<St, Fut> TakeUntil<St, Fut>
where
St: Stream,
Fut: Future,
{
/// Extract the stopping future out of the combinator.
/// The future is returned only if it isn't resolved yet, ie. if the stream isn't stopped yet.
/// Taking out the future means the combinator will be yielding
/// elements from the wrapped stream without ever stopping it.
pub fn take_future(&mut self) -> Option<Fut> {
if self.fut.is_some() {
self.free = true;
}

self.fut.take()
}

/// Once the stopping future is resolved, this method can be used
/// to extract the value returned by the stopping future.
///
/// This may be used to retrieve arbitrary data from the stopping
/// future, for example a reason why the stream was stopped.
///
/// This method will return `None` if the future isn't resolved yet,
/// or if the result was already taken out.
///
/// # Examples
///
/// ```
/// # spin_on::spin_on(async {
/// use futures_lite::stream::{self, StreamExt};
/// use futures_lite::future;
/// use std::task::Poll;
///
/// let stream = stream::iter(1..=10);
///
/// let mut i = 0;
/// let stop_fut = future::poll_fn(|_cx| {
/// i += 1;
/// if i <= 5 {
/// Poll::Pending
/// } else {
/// Poll::Ready("reason")
/// }
/// });
///
/// let mut stream = stream.take_until(stop_fut);
/// let _ = (&mut stream).collect::<Vec<_>>().await;
///
/// let result = stream.take_result().unwrap();
/// assert_eq!(result, "reason");
/// # });
/// ```
pub fn take_result(&mut self) -> Option<Fut::Output> {
self.fut_result.take()
}

/// Whether the stream was stopped yet by the stopping future
/// being resolved.
pub fn is_stopped(&self) -> bool {
!self.free && self.fut.is_none()
}
}

impl<St, Fut> Stream for TakeUntil<St, Fut>
where
St: Stream,
Fut: Future,
{
type Item = St::Item;

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

if let Some(f) = this.fut.as_mut().as_pin_mut() {
if let Poll::Ready(result) = f.poll(cx) {
this.fut.set(None);
*this.fut_result = Some(result);
}
}

if !*this.free && this.fut.is_none() {
// Future resolved, inner stream stopped
Poll::Ready(None)
} else {
// Future either not resolved yet or taken out by the user
let item = ready!(this.stream.poll_next(cx));
if item.is_none() {
this.fut.set(None);
}
Poll::Ready(item)
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
if self.is_stopped() {
return (0, Some(0));
}

self.stream.size_hint()
}
}

pin_project! {
/// Stream for the [`StreamExt::skip()`] method.
#[derive(Clone, Debug)]
Expand Down
Loading