Skip to content

feat: Implement find combinator for StreamExt #2950

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
101 changes: 101 additions & 0 deletions futures-util/src/stream/stream/find.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use crate::fns::FnMut1;
use crate::Stream;

use core::fmt;
use core::future::Future;
use core::pin::Pin;
use core::task::{ready, Context, Poll};
use futures_core::FusedFuture;
use pin_project_lite::pin_project;

pin_project! {
/// Future for the [`find`](super::StreamExt::find) method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Find<St, Fut, F>
where St: Stream,
{
#[pin]
stream: St,
f: F,
done: bool,
#[pin]
pending_fut: Option<Fut>,
pending_item: Option<St::Item>,
}
}

impl<St, Fut, F> fmt::Debug for Find<St, Fut, F>
where
St: Stream + fmt::Debug,
St::Item: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Find")
.field("stream", &self.stream)
.field("done", &self.done)
.field("pending_fut", &self.pending_fut)
.field("pending_item", &self.pending_item)
.finish()
}
}

impl<St, Fut, F> Find<St, Fut, F>
where
St: Stream,
F: for<'a> FnMut1<&'a St::Item, Output = Fut>,
Fut: Future<Output = bool>,
{
pub(super) fn new(stream: St, f: F) -> Self {
Self { stream, f, done: false, pending_fut: None, pending_item: None }
}
}

impl<St, Fut, F> FusedFuture for Find<St, Fut, F>
where
St: Stream,
F: FnMut(&St::Item) -> Fut,
Fut: Future<Output = bool>,
{
fn is_terminated(&self) -> bool {
self.done && self.pending_fut.is_none()
}
}

impl<St, Fut, F> Future for Find<St, Fut, F>
where
St: futures_core::Stream,
F: for<'a> FnMut1<&'a St::Item, Output = Fut>,
Fut: Future<Output = bool>,
{
type Output = Option<St::Item>;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> {
let mut this = self.project();
Poll::Ready(loop {
if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() {
// we're currently processing a future to produce a new value
let res = ready!(fut.poll(cx));
this.pending_fut.set(None);
if res {
*this.done = true;
break this.pending_item.take();
}
} else if !*this.done {
// we're waiting on a new item from the stream
match ready!(this.stream.as_mut().poll_next(cx)) {
Some(item) => {
this.pending_fut.set(Some(this.f.call_mut(&item)));
*this.pending_item = Some(item);
}
None => {
*this.done = true;
break None;
}
}
} else {
break None;
}
})
}
}
29 changes: 29 additions & 0 deletions futures-util/src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ pub use self::filter::Filter;
mod filter_map;
pub use self::filter_map::FilterMap;

mod find;
use self::find::Find;

mod flatten;

delegate_all!(
Expand Down Expand Up @@ -672,6 +675,32 @@ pub trait StreamExt: Stream {
assert_future::<T, _>(Fold::new(self, f, init))
}

/// Returns the first element in the stream that matches the given asynchronous predicate.
///
/// Searches through the stream and applies the provided asynchronous predicate to each element
/// until a match is found. Returns `Some(item)` with the matching element, or `None` if no
/// element matches the predicate.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::{future, stream::{self, StreamExt}};
///
/// let number_stream = stream::iter([1, 3, 6, 5, 9]);
/// let first_even = number_stream.find(|x| future::ready(x % 2 == 0));
/// assert_eq!(first_even.await, Some(6));
/// # });
/// ```
fn find<Fut, F>(self, f: F) -> Find<Self, Fut, F>
where
Self: Sized,
F: FnMut(&Self::Item) -> Fut,
Fut: Future<Output = bool>,
{
assert_future::<Option<Self::Item>, _>(Find::new(self, f))
}

/// Execute predicate over asynchronous stream, and return `true` if any element in stream satisfied a predicate.
///
/// # Examples
Expand Down