File tree Expand file tree Collapse file tree 2 files changed +12
-7
lines changed Expand file tree Collapse file tree 2 files changed +12
-7
lines changed Original file line number Diff line number Diff line change @@ -318,7 +318,7 @@ extension_trait! {
318
318
#[ doc = r#"
319
319
Limit the amount of items yielded per timeslice in a stream.
320
320
321
- This stream does not drop any items, but will only limit the rate at which items pass through.
321
+ This stream does not drop any items, but will only limit the rate at which items pass through.
322
322
# Examples
323
323
```
324
324
# fn main() { async_std::task::block_on(async {
Original file line number Diff line number Diff line change 1
1
use std:: future:: Future ;
2
2
use std:: pin:: Pin ;
3
- use std:: time:: Duration ;
3
+ use std:: time:: { Duration , Instant } ;
4
4
5
5
use futures_timer:: Delay ;
6
6
use pin_project_lite:: pin_project;
@@ -23,7 +23,9 @@ pin_project! {
23
23
stream: S ,
24
24
duration: Duration ,
25
25
#[ pin]
26
- delay: Option <Delay >,
26
+ blocked: bool ,
27
+ #[ pin]
28
+ delay: Delay ,
27
29
}
28
30
}
29
31
@@ -32,7 +34,8 @@ impl<S: Stream> Throttle<S> {
32
34
Throttle {
33
35
stream,
34
36
duration,
35
- delay : None ,
37
+ blocked : false ,
38
+ delay : Delay :: new ( Duration :: default ( ) ) ,
36
39
}
37
40
}
38
41
}
@@ -42,9 +45,10 @@ impl<S: Stream> Stream for Throttle<S> {
42
45
43
46
fn poll_next ( self : Pin < & mut Self > , cx : & mut Context < ' _ > ) -> Poll < Option < S :: Item > > {
44
47
let mut this = self . project ( ) ;
45
- if let Some ( d) = this. delay . as_mut ( ) . as_pin_mut ( ) {
48
+ if * this. blocked {
49
+ let d = this. delay . as_mut ( ) ;
46
50
if d. poll ( cx) . is_ready ( ) {
47
- this. delay . set ( None ) ;
51
+ * this. blocked = false ;
48
52
} else {
49
53
return Poll :: Pending ;
50
54
}
@@ -57,7 +61,8 @@ impl<S: Stream> Stream for Throttle<S> {
57
61
}
58
62
Poll :: Ready ( None ) => Poll :: Ready ( None ) ,
59
63
Poll :: Ready ( Some ( v) ) => {
60
- this. delay . set ( Some ( Delay :: new ( * this. duration ) ) ) ;
64
+ * this. blocked = true ;
65
+ this. delay . reset ( Instant :: now ( ) + * this. duration ) ;
61
66
Poll :: Ready ( Some ( v) )
62
67
}
63
68
}
You can’t perform that action at this time.
0 commit comments