Skip to main content

rh_foundation/memory/
stats.rs

1use std::sync::Arc;
2
3use parking_lot::RwLock;
4
5/// Statistics for a memory store.
6#[derive(Debug, Clone, Default)]
7pub struct MemoryStoreStats {
8    /// Number of cache hits.
9    pub hits: u64,
10    /// Number of cache misses.
11    pub misses: u64,
12    /// Number of insertions.
13    pub insertions: u64,
14    /// Number of removals.
15    pub removals: u64,
16    /// Number of evictions due to capacity limits.
17    pub evictions: u64,
18}
19
20impl MemoryStoreStats {
21    /// Calculate the hit rate (0.0 to 1.0).
22    pub fn hit_rate(&self) -> f64 {
23        let total = self.hits + self.misses;
24        if total == 0 {
25            0.0
26        } else {
27            self.hits as f64 / total as f64
28        }
29    }
30}
31
32#[derive(Debug, Clone)]
33pub(super) struct StatsRecorder {
34    enabled: bool,
35    stats: Arc<RwLock<MemoryStoreStats>>,
36}
37
38impl StatsRecorder {
39    pub(super) fn new(enabled: bool) -> Self {
40        Self {
41            enabled,
42            stats: Arc::new(RwLock::new(MemoryStoreStats::default())),
43        }
44    }
45
46    pub(super) fn snapshot(&self) -> MemoryStoreStats {
47        self.stats.read().clone()
48    }
49
50    pub(super) fn reset(&self) {
51        *self.stats.write() = MemoryStoreStats::default();
52    }
53
54    pub(super) fn record_hit(&self) {
55        self.update(|stats| stats.hits += 1);
56    }
57
58    pub(super) fn record_miss(&self) {
59        self.update(|stats| stats.misses += 1);
60    }
61
62    pub(super) fn record_insertion(&self) {
63        self.update(|stats| stats.insertions += 1);
64    }
65
66    pub(super) fn record_removal(&self) {
67        self.update(|stats| stats.removals += 1);
68    }
69
70    pub(super) fn record_eviction(&self) {
71        self.update(|stats| stats.evictions += 1);
72    }
73
74    fn update(&self, apply: impl FnOnce(&mut MemoryStoreStats)) {
75        if !self.enabled {
76            return;
77        }
78
79        let mut stats = self.stats.write();
80        apply(&mut stats);
81    }
82}