Skip to content

Commit

Permalink
Merge pull request #368 from starsheriff/stream_count
Browse files Browse the repository at this point in the history
add stream::count
  • Loading branch information
yoshuawuyts authored Nov 14, 2019
2 parents f49d7cb + 9ebe41f commit c58747b
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
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 @@ -68,6 +69,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 @@ -1889,6 +1891,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

0 comments on commit c58747b

Please sign in to comment.