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 ParallelStream::count #11

Open
wants to merge 1 commit 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
54 changes: 54 additions & 0 deletions src/par_stream/count.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use async_std::prelude::*;
use async_std::task::{self, Context, Poll};

use std::pin::Pin;

use crate::ParallelStream;

pin_project_lite::pin_project! {
/// Count the number of items of the stream.
///
/// This `struct` is created by the [`count`] method on [`ParallelStream`]. See its
/// documentation for more.
///
/// [`count`]: trait.ParallelStream.html#method.count
/// [`ParallelStream`]: trait.ParallelStream.html
#[derive(Clone, Debug)]
pub struct Count<S> {
#[pin]
stream: S,
count: usize,
}
}

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

impl<S: ParallelStream> Future for Count<S> {
type Output = usize;

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

match task::ready!(this.stream.poll_next(cx)) {
None => Poll::Ready(*this.count),
Some(_) => {
*this.count += 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
}

#[async_std::test]
async fn smoke() {
let s = async_std::stream::repeat(5usize);

let cnt = crate::from_stream(s).take(10).count().await;

assert_eq!(cnt, 10);
}
7 changes: 7 additions & 0 deletions src/par_stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ use std::pin::Pin;

use crate::FromParallelStream;

pub use count::Count;
pub use for_each::ForEach;
pub use map::Map;
pub use next::NextFuture;
pub use take::Take;

mod count;
mod for_each;
mod map;
mod next;
Expand All @@ -29,6 +31,11 @@ pub trait ParallelStream: Sized + Send + Sync + Unpin + 'static {
/// Get the max concurrency limit
fn get_limit(&self) -> Option<usize>;

/// Counts the number of items of this stream.
fn count(self) -> Count<Self> {
Count::new(self)
}

/// Applies `f` to each item of this stream in parallel, producing a new
/// stream with the results.
fn map<F, T, Fut>(self, f: F) -> Map<T>
Expand Down