Skip to main content

rill_ml/stats/
count.rs

1//! Online count of observations.
2//!
3//! Time complexity per update: `O(1)`. Space complexity: `O(1)`.
4
5use crate::error::{RillError, checked_increment};
6use crate::traits::OnlineStatistic;
7
8/// A simple observation counter.
9#[derive(Debug, Clone, Default)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct Count {
12    count: u64,
13}
14
15impl Count {
16    /// Create a new counter.
17    pub const fn new() -> Self {
18        Self { count: 0 }
19    }
20
21    /// Current count.
22    pub const fn value(&self) -> u64 {
23        self.count
24    }
25}
26
27impl OnlineStatistic for Count {
28    fn update(&mut self, _value: f64) -> Result<(), RillError> {
29        self.count = checked_increment(self.count, "count sample")?;
30        Ok(())
31    }
32
33    fn samples_seen(&self) -> u64 {
34        self.count
35    }
36
37    fn reset(&mut self) {
38        self.count = 0;
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn count_increments() {
48        let mut c = Count::new();
49        c.update(1.0).unwrap();
50        c.update(2.0).unwrap();
51        assert_eq!(c.value(), 2);
52    }
53}