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;
25
25
mod any;
26
26
mod chain;
27
27
mod cmp;
28
+ mod count;
28
29
mod enumerate;
29
30
mod filter;
30
31
mod filter_map;
@@ -57,6 +58,7 @@ mod zip;
57
58
use all:: AllFuture ;
58
59
use any:: AnyFuture ;
59
60
use cmp:: CmpFuture ;
61
+ use count:: CountFuture ;
60
62
use enumerate:: Enumerate ;
61
63
use filter_map:: FilterMap ;
62
64
use find:: FindFuture ;
@@ -1392,6 +1394,33 @@ extension_trait! {
1392
1394
CmpFuture :: new( self , other)
1393
1395
}
1394
1396
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
+
1395
1424
#[ doc = r#"
1396
1425
Determines if the elements of this `Stream` are lexicographically
1397
1426
greater than or equal to those of another.
You can’t perform that action at this time.
0 commit comments