ratel_bandit/util/counter/
record_counter.rs

1use std::ops::AddAssign;
2
3use num_traits::{Num, ToPrimitive};
4
5use super::Counter;
6
7/// Counter for cases where individual records must be maintained.
8pub struct RecordCounter<T: ToPrimitive> {
9    /// Vector of records passed to counter
10    record: Vec<T>,
11    /// Count of all elements passed to counter.
12    counter: T,
13}
14
15impl<T: Num + ToPrimitive> RecordCounter<T> {
16    /// Initializes counter to zero and record to empty
17    pub fn new() -> RecordCounter<T> {
18        RecordCounter {
19            record: Vec::new(),
20            counter: T::zero(),
21        }
22    }
23
24    /// Returns the current vector of records.
25    pub fn record(&self) -> &Vec<T> {
26        &self.record
27    }
28}
29
30impl<T: AddAssign + Num + ToPrimitive> Counter<T> for RecordCounter<T> {
31    /// Returns the current value of the counter.
32    fn counter(&self) -> &T {
33        &self.counter
34    }
35
36    /// Resets counter to initial values.
37    fn reset(&mut self) {
38        self.record = Vec::new();
39        self.counter = T::zero()
40    }
41
42    /// Updates counter with new value.
43    fn update(&mut self, n: T) {
44        self.record.push(n);
45        self.counter += T::one()
46    }
47}
48
49impl<T: Num + ToPrimitive> Default for RecordCounter<T> {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::RecordCounter;
58    use super::super::Counter;
59
60    lazy_static! {
61        static ref NUMS_VEC: Vec<i32> = vec![45, 5, 52, 93, 51, 90];
62        static ref DEC_VEC: Vec<u32> = vec![79, 42, 11, 29, 76];
63        static ref FLOAT_VEC: Vec<f64> = vec![9.62, 4.0, 4.6, 7.73, 7.59];
64    }
65
66    #[test]
67    fn test_record_counter() {
68        let mut ac: RecordCounter<i32> = RecordCounter::new();
69        for i in 0..=5 {
70            ac.update(NUMS_VEC[i])
71        }
72        assert_eq!(*ac.counter(), 6);
73        assert_eq!(ac.record()[2], 52);
74        ac.reset();
75
76        assert_eq!(*ac.counter(), 0);
77        for _ in 1..=7 {
78            ac.update(3)
79        }
80        assert_eq!(*ac.counter(), 7);
81    }
82
83    #[test]
84    fn test_record_int_counter() {
85        let mut ac: RecordCounter<u32> = RecordCounter::new();
86        for i in 0..=4 {
87            ac.update(DEC_VEC[i])
88        }
89        assert_eq!(*ac.counter(), 5);
90        assert_eq!(ac.record()[2], 11);
91        ac.reset();
92        assert_eq!(*ac.counter(), 0);
93    }
94
95    #[test]
96    fn test_record_float_counter() {
97        let mut ac: RecordCounter<f64> = RecordCounter::new();
98        for i in 0..=4 {
99            ac.update(FLOAT_VEC[i])
100        }
101        assert_eq!(*ac.counter(), 5.0);
102        assert_eq!(ac.record()[2], 4.6);
103        ac.reset();
104        assert_eq!(*ac.counter(), 0.0);
105    }
106}