@@ -11,17 +11,17 @@ pub struct MetricsCounter<const N: usize> {
11
11
12
12
impl < const N : usize > MetricsCounter < N > {
13
13
/// Creates a new counter with an initial value.
14
- pub fn new ( init : usize ) -> Self {
14
+ pub fn new ( init : usize , init_at : Instant ) -> Self {
15
15
debug_assert ! ( N > 0 , "number of slots must be greater than zero" ) ;
16
16
Self {
17
- slots : [ ( init, Instant :: now ( ) ) ; N ] ,
17
+ slots : [ ( init, init_at ) ; N ] ,
18
18
index : 0 ,
19
19
}
20
20
}
21
21
22
22
/// Adds record to the counter.
23
- pub fn add ( & mut self , data : usize ) {
24
- self . slots [ self . index ] = ( data, Instant :: now ( ) ) ;
23
+ pub fn add ( & mut self , data : usize , added_at : Instant ) {
24
+ self . slots [ self . index ] = ( data, added_at ) ;
25
25
self . index = ( self . index + 1 ) % N ;
26
26
}
27
27
@@ -42,20 +42,26 @@ impl<const N: usize> MetricsCounter<N> {
42
42
#[ cfg( test) ]
43
43
mod tests {
44
44
use super :: MetricsCounter ;
45
+ use std:: time:: { Duration , Instant } ;
45
46
46
47
#[ test]
47
48
fn counter ( ) {
48
- let mut counter = MetricsCounter :: < 3 > :: new ( 0 ) ;
49
+ let now = Instant :: now ( ) ;
50
+ let mut counter = MetricsCounter :: < 3 > :: new ( 0 , now) ;
49
51
assert_eq ! ( counter. rate( ) , 0f32 ) ;
50
- for i in 1 ..=5 {
51
- counter. add ( i) ;
52
- assert ! ( counter. rate( ) > 0f32 ) ;
53
- }
52
+ counter. add ( 1 , now + Duration :: from_secs ( 1 ) ) ;
53
+ assert_eq ! ( counter. rate( ) , 1f32 ) ;
54
+ counter. add ( 4 , now + Duration :: from_secs ( 2 ) ) ;
55
+ assert_eq ! ( counter. rate( ) , 2f32 ) ;
56
+ counter. add ( 7 , now + Duration :: from_secs ( 3 ) ) ;
57
+ assert_eq ! ( counter. rate( ) , 3f32 ) ;
58
+ counter. add ( 12 , now + Duration :: from_secs ( 4 ) ) ;
59
+ assert_eq ! ( counter. rate( ) , 4f32 ) ;
54
60
}
55
61
56
62
#[ test]
57
63
#[ should_panic( expected = "number of slots must be greater than zero" ) ]
58
64
fn counter_zero_slot ( ) {
59
- let _counter = MetricsCounter :: < 0 > :: new ( 0 ) ;
65
+ let _counter = MetricsCounter :: < 0 > :: new ( 0 , Instant :: now ( ) ) ;
60
66
}
61
67
}
0 commit comments