Skip to content

Commit a9a7bdc

Browse files
committed
add stream::count
1 parent ec23632 commit a9a7bdc

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

src/stream/stream/count.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
use std::pin::Pin;
2+
3+
use crate::future::Future;
4+
use crate::stream::Stream;
5+
use crate::task::{Context, Poll};
6+
7+
#[doc(hidden)]
8+
#[allow(missing_debug_implementations)]
9+
pub struct CountFuture<S> {
10+
stream: S,
11+
count: usize,
12+
}
13+
14+
impl<S> CountFuture<S> {
15+
pin_utils::unsafe_pinned!(stream: S);
16+
pin_utils::unsafe_unpinned!(count: usize);
17+
18+
pub(crate) fn new(stream: S) -> Self {
19+
CountFuture { stream, count: 0 }
20+
}
21+
}
22+
23+
impl<S> Future for CountFuture<S>
24+
where
25+
S: Sized + Stream,
26+
{
27+
type Output = usize;
28+
29+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
30+
let next = futures_core::ready!(self.as_mut().stream().poll_next(cx));
31+
32+
match next {
33+
Some(_) => {
34+
cx.waker().wake_by_ref();
35+
*self.as_mut().count() += 1;
36+
Poll::Pending
37+
}
38+
None => Poll::Ready(self.count),
39+
}
40+
}
41+
}

src/stream/stream/mod.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ mod all;
2525
mod any;
2626
mod chain;
2727
mod cmp;
28+
mod count;
2829
mod enumerate;
2930
mod filter;
3031
mod filter_map;
@@ -57,6 +58,7 @@ mod zip;
5758
use all::AllFuture;
5859
use any::AnyFuture;
5960
use cmp::CmpFuture;
61+
use count::CountFuture;
6062
use enumerate::Enumerate;
6163
use filter_map::FilterMap;
6264
use find::FindFuture;
@@ -1392,6 +1394,33 @@ extension_trait! {
13921394
CmpFuture::new(self, other)
13931395
}
13941396

1397+
#[doc = r#"
1398+
Counts the number of elements in the stream.
1399+
1400+
# Examples
1401+
1402+
```
1403+
# fn main() { async_std::task::block_on(async {
1404+
#
1405+
use async_std::prelude::*;
1406+
use std::collections::VecDeque;
1407+
1408+
let s1 = VecDeque::from(vec![0]);
1409+
let s2 = VecDeque::from(vec![1, 2, 3]);
1410+
1411+
assert_eq!(s1.count().await, 1);
1412+
assert_eq!(s2.count().await, 3);
1413+
#
1414+
# }) }
1415+
```
1416+
"#]
1417+
fn count(self) -> impl Future<Output = Ordering> [CountFuture<Self>]
1418+
where
1419+
Self: Sized + Stream,
1420+
{
1421+
CountFuture::new(self)
1422+
}
1423+
13951424
#[doc = r#"
13961425
Determines if the elements of this `Stream` are lexicographically
13971426
greater than or equal to those of another.

0 commit comments

Comments
 (0)