@@ -84,6 +84,11 @@ impl<N, A: Atomic<N>> Counter<N, A> {
84
84
self . value . inc_by ( v)
85
85
}
86
86
87
+ /// Resets the [`Counter`] to `0`, returning the previous value.
88
+ pub fn reset ( & self ) -> N {
89
+ self . value . reset ( )
90
+ }
91
+
87
92
/// Get the current value of the [`Counter`].
88
93
pub fn get ( & self ) -> N {
89
94
self . value . get ( )
@@ -110,6 +115,9 @@ pub trait Atomic<N> {
110
115
/// Increase the value.
111
116
fn inc_by ( & self , v : N ) -> N ;
112
117
118
+ /// Reset the value to `0`.
119
+ fn reset ( & self ) -> N ;
120
+
113
121
/// Get the the value.
114
122
fn get ( & self ) -> N ;
115
123
}
@@ -124,6 +132,10 @@ impl Atomic<u64> for AtomicU64 {
124
132
self . fetch_add ( v, Ordering :: Relaxed )
125
133
}
126
134
135
+ fn reset ( & self ) -> u64 {
136
+ self . swap ( Default :: default ( ) , Ordering :: Relaxed )
137
+ }
138
+
127
139
fn get ( & self ) -> u64 {
128
140
self . load ( Ordering :: Relaxed )
129
141
}
@@ -138,6 +150,10 @@ impl Atomic<u32> for AtomicU32 {
138
150
self . fetch_add ( v, Ordering :: Relaxed )
139
151
}
140
152
153
+ fn reset ( & self ) -> u32 {
154
+ self . swap ( Default :: default ( ) , Ordering :: Relaxed )
155
+ }
156
+
141
157
fn get ( & self ) -> u32 {
142
158
self . load ( Ordering :: Relaxed )
143
159
}
@@ -164,6 +180,10 @@ impl Atomic<f64> for AtomicU64 {
164
180
old_f64
165
181
}
166
182
183
+ fn reset ( & self ) -> f64 {
184
+ f64:: from_bits ( self . swap ( Default :: default ( ) , Ordering :: Relaxed ) )
185
+ }
186
+
167
187
fn get ( & self ) -> f64 {
168
188
f64:: from_bits ( self . load ( Ordering :: Relaxed ) )
169
189
}
@@ -231,6 +251,14 @@ mod tests {
231
251
assert_eq ! ( 1 , counter. get( ) ) ;
232
252
}
233
253
254
+ #[ test]
255
+ fn inc_reset_and_get ( ) {
256
+ let counter: Counter = Counter :: default ( ) ;
257
+ assert_eq ! ( 0 , counter. inc( ) ) ;
258
+ assert_eq ! ( 1 , counter. reset( ) ) ;
259
+ assert_eq ! ( 0 , counter. get( ) ) ;
260
+ }
261
+
234
262
#[ cfg( not( any( target_arch = "mips" , target_arch = "powerpc" ) ) ) ]
235
263
#[ test]
236
264
fn f64_stored_in_atomic_u64 ( ) {
0 commit comments