1
1
//! Task-notifying counter.
2
2
3
- use core:: { cell:: Cell , task} ;
3
+ use core:: { cell:: Cell , fmt , task} ;
4
4
use std:: rc:: Rc ;
5
5
6
6
use local_waker:: LocalWaker ;
7
7
8
- #[ derive( Clone ) ]
9
8
/// Simple counter with ability to notify task on reaching specific number
10
9
///
11
10
/// Counter could be cloned, total n-count is shared across all clones.
11
+ #[ derive( Debug , Clone ) ]
12
12
pub struct Counter ( Rc < CounterInner > ) ;
13
13
14
- struct CounterInner {
15
- count : Cell < usize > ,
16
- capacity : usize ,
17
- task : LocalWaker ,
18
- }
19
-
20
14
impl Counter {
21
- /// Create `Counter` instance and set max value.
15
+ /// Create `Counter` instance with max value.
22
16
pub fn new ( capacity : usize ) -> Self {
23
17
Counter ( Rc :: new ( CounterInner {
24
18
capacity,
@@ -27,38 +21,26 @@ impl Counter {
27
21
} ) )
28
22
}
29
23
30
- /// Get counter guard.
24
+ /// Create new counter guard, incrementing the counter .
31
25
pub fn get ( & self ) -> CounterGuard {
32
26
CounterGuard :: new ( self . 0 . clone ( ) )
33
27
}
34
28
35
- /// Check if counter is not at capacity. If counter at capacity
36
- /// it registers notification for current task.
29
+ /// Notify current task and return true if counter is at capacity.
37
30
pub fn available ( & self , cx : & mut task:: Context < ' _ > ) -> bool {
38
31
self . 0 . available ( cx)
39
32
}
40
33
41
- /// Get total number of acquired counts
34
+ /// Get total number of acquired guards.
42
35
pub fn total ( & self ) -> usize {
43
36
self . 0 . count . get ( )
44
37
}
45
38
}
46
39
47
- pub struct CounterGuard ( Rc < CounterInner > ) ;
48
-
49
- impl CounterGuard {
50
- fn new ( inner : Rc < CounterInner > ) -> Self {
51
- inner. inc ( ) ;
52
- CounterGuard ( inner)
53
- }
54
- }
55
-
56
- impl Unpin for CounterGuard { }
57
-
58
- impl Drop for CounterGuard {
59
- fn drop ( & mut self ) {
60
- self . 0 . dec ( ) ;
61
- }
40
+ struct CounterInner {
41
+ count : Cell < usize > ,
42
+ capacity : usize ,
43
+ task : LocalWaker ,
62
44
}
63
45
64
46
impl CounterInner {
@@ -83,3 +65,32 @@ impl CounterInner {
83
65
}
84
66
}
85
67
}
68
+
69
+ impl fmt:: Debug for CounterInner {
70
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
71
+ f. debug_struct ( "Counter" )
72
+ . field ( "count" , & self . count . get ( ) )
73
+ . field ( "capacity" , & self . capacity )
74
+ . field ( "task" , & self . task )
75
+ . finish ( )
76
+ }
77
+ }
78
+
79
+ /// An RAII structure that keeps the underlying counter incremented until this guard is dropped.
80
+ #[ derive( Debug ) ]
81
+ pub struct CounterGuard ( Rc < CounterInner > ) ;
82
+
83
+ impl CounterGuard {
84
+ fn new ( inner : Rc < CounterInner > ) -> Self {
85
+ inner. inc ( ) ;
86
+ CounterGuard ( inner)
87
+ }
88
+ }
89
+
90
+ impl Unpin for CounterGuard { }
91
+
92
+ impl Drop for CounterGuard {
93
+ fn drop ( & mut self ) {
94
+ self . 0 . dec ( ) ;
95
+ }
96
+ }
0 commit comments