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 Stream count #527

Closed
wants to merge 1 commit into from
Closed
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
47 changes: 47 additions & 0 deletions src/stream/stream/count.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use std::pin::Pin;
use std::future::Future;

use pin_project_lite::pin_project;

use crate::stream::Stream;
use crate::task::{Context, Poll};

pin_project! {
#[doc(hidden)]
#[allow(missing_debug_implementations)]
pub struct CountFuture<S> {
#[pin]
stream: S,
count: usize,
}
}

impl<S> CountFuture<S> {
pub(super) fn new(stream: S) -> Self {
Self {
stream,
count: 0,
}
}
}

impl<S> Future for CountFuture<S>
where
S: Stream,
{
type Output = usize;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let next = futures_core::ready!(this.stream.poll_next(cx));

match next {
Some(_) => {
cx.waker().wake_by_ref();
*this.count += 1;
Poll::Pending
}
None => Poll::Ready(*this.count),
}
}
}
31 changes: 31 additions & 0 deletions src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ mod chain;
mod cloned;
mod cmp;
mod copied;
mod count;
mod cycle;
mod enumerate;
mod eq;
Expand Down Expand Up @@ -67,6 +68,7 @@ mod zip;
use all::AllFuture;
use any::AnyFuture;
use cmp::CmpFuture;
use count::CountFuture;
use cycle::Cycle;
use enumerate::Enumerate;
use eq::EqFuture;
Expand Down Expand Up @@ -912,6 +914,35 @@ extension_trait! {
MinByFuture::new(self, compare)
}

#[doc = r#"
Counting the number of elements and returning it.

# Examples

```ignore
# fn main() { async_std::task::block_on(async {
#
use async_std::prelude::*;
use async_std::stream;

let s = stream::from_iter(vec![1, 2, 3]);

let count = s.count().await;
assert_eq!(count, 3);

#
# }) }
```
"#]
fn count<F>(
self,
) -> impl Future<Output = usize> [CountFuture<Self>]
where
Self: Sized,
{
CountFuture::new(self)
}

#[doc = r#"
Returns the element that gives the minimum value. If several elements are equally minimum,
the first element is returned. If the stream is empty, `None` is returned.
Expand Down