reinhardt_utils/cache/statistics.rs
1//! Cache statistics and entry information
2
3/// Cache entry information for inspection
4#[derive(Debug, Clone)]
5pub struct CacheEntryInfo {
6 /// The key of the entry
7 pub key: String,
8 /// Size of the value in bytes
9 pub size: usize,
10 /// Whether the entry has an expiration time
11 pub has_expiry: bool,
12 /// Seconds until expiration (if applicable)
13 pub ttl_seconds: Option<u64>,
14}
15
16/// Cache statistics
17#[derive(Debug, Clone, Default)]
18pub struct CacheStatistics {
19 /// Number of cache hits
20 pub hits: u64,
21 /// Number of cache misses
22 pub misses: u64,
23 /// Total number of requests
24 pub total_requests: u64,
25 /// Current number of entries in cache
26 pub entry_count: u64,
27 /// Approximate memory usage in bytes
28 pub memory_usage: u64,
29}
30
31impl CacheStatistics {
32 /// Calculate hit rate (0.0 to 1.0)
33 ///
34 /// # Examples
35 ///
36 /// ```
37 /// use reinhardt_utils::cache::CacheStatistics;
38 ///
39 /// let mut stats = CacheStatistics::default();
40 /// stats.hits = 75;
41 /// stats.misses = 25;
42 /// stats.total_requests = 100;
43 ///
44 /// assert_eq!(stats.hit_rate(), 0.75);
45 /// ```
46 pub fn hit_rate(&self) -> f64 {
47 if self.total_requests == 0 {
48 0.0
49 } else {
50 self.hits as f64 / self.total_requests as f64
51 }
52 }
53
54 /// Calculate miss rate (0.0 to 1.0)
55 ///
56 /// # Examples
57 ///
58 /// ```
59 /// use reinhardt_utils::cache::CacheStatistics;
60 ///
61 /// let mut stats = CacheStatistics::default();
62 /// stats.hits = 75;
63 /// stats.misses = 25;
64 /// stats.total_requests = 100;
65 ///
66 /// assert_eq!(stats.miss_rate(), 0.25);
67 /// ```
68 pub fn miss_rate(&self) -> f64 {
69 if self.total_requests == 0 {
70 0.0
71 } else {
72 self.misses as f64 / self.total_requests as f64
73 }
74 }
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[tokio::test]
82 async fn test_statistics_hit_miss_rate_zero_requests() {
83 let stats = CacheStatistics::default();
84 assert_eq!(stats.hit_rate(), 0.0);
85 assert_eq!(stats.miss_rate(), 0.0);
86 }
87}