File tree Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change @@ -25,6 +25,7 @@ mod all;
2525mod any;
2626mod chain;
2727mod cmp;
28+ mod count;
2829mod enumerate;
2930mod filter;
3031mod filter_map;
@@ -57,6 +58,7 @@ mod zip;
5758use all:: AllFuture ;
5859use any:: AnyFuture ;
5960use cmp:: CmpFuture ;
61+ use count:: CountFuture ;
6062use enumerate:: Enumerate ;
6163use filter_map:: FilterMap ;
6264use 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.
You can’t perform that action at this time.
0 commit comments