Skip to content

Commit

Permalink
StreamExt::All / StreamExt::Any (#2460)
Browse files Browse the repository at this point in the history
Closes #2458

Co-authored-by: Marek Barvir <barvir@cadwork.cz>
  • Loading branch information
2 people authored and taiki-e committed Jul 23, 2021
1 parent c04f3a4 commit b8664e9
Show file tree
Hide file tree
Showing 3 changed files with 236 additions and 0 deletions.
92 changes: 92 additions & 0 deletions futures-util/src/stream/stream/all.rs
@@ -0,0 +1,92 @@
use core::fmt;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::ready;
use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use pin_project_lite::pin_project;

pin_project! {
/// Future for the [`all`](super::StreamExt::all) method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct All<St, Fut, F> {
#[pin]
stream: St,
f: F,
accum: Option<bool>,
#[pin]
future: Option<Fut>,
}
}

impl<St, Fut, F> fmt::Debug for All<St, Fut, F>
where
St: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("All")
.field("stream", &self.stream)
.field("accum", &self.accum)
.field("future", &self.future)
.finish()
}
}

impl<St, Fut, F> All<St, Fut, F>
where
St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = bool>,
{
pub(super) fn new(stream: St, f: F) -> Self {
Self { stream, f, accum: Some(true), future: None }
}
}

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

impl<St, Fut, F> Future for All<St, Fut, F>
where
St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = bool>,
{
type Output = bool;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<bool> {
let mut this = self.project();
Poll::Ready(loop {
if let Some(fut) = this.future.as_mut().as_pin_mut() {
// we're currently processing a future to produce a new accum value
let acc = this.accum.unwrap() && ready!(fut.poll(cx));
if !acc {
break false;
} // early exit
*this.accum = Some(acc);
this.future.set(None);
} else if this.accum.is_some() {
// we're waiting on a new item from the stream
match ready!(this.stream.as_mut().poll_next(cx)) {
Some(item) => {
this.future.set(Some((this.f)(item)));
}
None => {
break this.accum.take().unwrap();
}
}
} else {
panic!("All polled after completion")
}
})
}
}
92 changes: 92 additions & 0 deletions futures-util/src/stream/stream/any.rs
@@ -0,0 +1,92 @@
use core::fmt;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::ready;
use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use pin_project_lite::pin_project;

pin_project! {
/// Future for the [`any`](super::StreamExt::any) method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Any<St, Fut, F> {
#[pin]
stream: St,
f: F,
accum: Option<bool>,
#[pin]
future: Option<Fut>,
}
}

impl<St, Fut, F> fmt::Debug for Any<St, Fut, F>
where
St: fmt::Debug,
Fut: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Any")
.field("stream", &self.stream)
.field("accum", &self.accum)
.field("future", &self.future)
.finish()
}
}

impl<St, Fut, F> Any<St, Fut, F>
where
St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = bool>,
{
pub(super) fn new(stream: St, f: F) -> Self {
Self { stream, f, accum: Some(false), future: None }
}
}

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

impl<St, Fut, F> Future for Any<St, Fut, F>
where
St: Stream,
F: FnMut(St::Item) -> Fut,
Fut: Future<Output = bool>,
{
type Output = bool;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<bool> {
let mut this = self.project();
Poll::Ready(loop {
if let Some(fut) = this.future.as_mut().as_pin_mut() {
// we're currently processing a future to produce a new accum value
let acc = this.accum.unwrap() || ready!(fut.poll(cx));
if acc {
break true;
} // early exit
*this.accum = Some(acc);
this.future.set(None);
} else if this.accum.is_some() {
// we're waiting on a new item from the stream
match ready!(this.stream.as_mut().poll_next(cx)) {
Some(item) => {
this.future.set(Some((this.f)(item)));
}
None => {
break this.accum.take().unwrap();
}
}
} else {
panic!("Any polled after completion")
}
})
}
}
52 changes: 52 additions & 0 deletions futures-util/src/stream/stream/mod.rs
Expand Up @@ -70,6 +70,14 @@ mod fold;
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::fold::Fold;

mod any;
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::any::Any;

mod all;
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::all::All;

#[cfg(feature = "sink")]
mod forward;

Expand Down Expand Up @@ -627,6 +635,50 @@ pub trait StreamExt: Stream {
assert_future::<T, _>(Fold::new(self, f, init))
}

/// Execute predicate over asynchronous stream, and return `true` if any element in stream satisfied a predicate.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::stream::{self, StreamExt};
///
/// let number_stream = stream::iter(0..10);
/// let contain_three = number_stream.any(|i| async move { i == 3 });
/// assert_eq!(contain_three.await, true);
/// # });
/// ```
fn any<Fut, F>(self, f: F) -> Any<Self, Fut, F>
where
F: FnMut(Self::Item) -> Fut,
Fut: Future<Output = bool>,
Self: Sized,
{
assert_future::<bool, _>(Any::new(self, f))
}

/// Execute predicate over asynchronous stream, and return `true` if all element in stream satisfied a predicate.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::stream::{self, StreamExt};
///
/// let number_stream = stream::iter(0..10);
/// let less_then_twenty = number_stream.all(|i| async move { i < 20 });
/// assert_eq!(less_then_twenty.await, true);
/// # });
/// ```
fn all<Fut, F>(self, f: F) -> All<Self, Fut, F>
where
F: FnMut(Self::Item) -> Fut,
Fut: Future<Output = bool>,
Self: Sized,
{
assert_future::<bool, _>(All::new(self, f))
}

/// Flattens a stream of streams into just one continuous stream.
///
/// # Examples
Expand Down

0 comments on commit b8664e9

Please sign in to comment.