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 #368

Merged
merged 8 commits into from
Nov 14, 2019
Merged
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
44 changes: 44 additions & 0 deletions src/stream/stream/count.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::future::Future;
use std::pin::Pin;

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(crate) fn new(stream: S) -> Self {
CountFuture { 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),
}
}
}
29 changes: 29 additions & 0 deletions src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ mod any;
mod chain;
mod cloned;
mod cmp;
mod count;
mod copied;
mod cycle;
mod enumerate;
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 @@ -1802,6 +1804,33 @@ extension_trait! {
CmpFuture::new(self, other)
}

#[doc = r#"
Counts the number of elements in the stream.

# Examples

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

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

assert_eq!(s1.count().await, 1);
assert_eq!(s2.count().await, 3);
#
# }) }
```
"#]
fn count(self) -> impl Future<Output = usize> [CountFuture<Self>]
where
Self: Sized,
{
CountFuture::new(self)
}

#[doc = r#"
Determines if the elements of this `Stream` are lexicographically
not equal to those of another.
Expand Down