cache_rs/config/
lfuda.rs

1//! Configuration for the Least Frequently Used with Dynamic Aging (LFUDA) cache.
2
3use core::fmt;
4use core::num::NonZeroUsize;
5
6/// Configuration for an LFUDA (Least Frequently Used with Dynamic Aging) cache.
7///
8/// LFUDA enhances LFU by using a dynamic aging mechanism that prevents old
9/// frequently-accessed items from permanently blocking new items.
10///
11/// # Examples
12///
13/// ```
14/// use cache_rs::config::lfuda::LfudaCacheConfig;
15/// use core::num::NonZeroUsize;
16///
17/// // Create a config with capacity of 100 items and initial age of 0
18/// let config = LfudaCacheConfig::new(NonZeroUsize::new(100).unwrap());
19///
20/// assert_eq!(config.capacity(), NonZeroUsize::new(100).unwrap());
21/// assert_eq!(config.initial_age(), 0);
22/// ```
23#[derive(Clone, Copy)]
24pub struct LfudaCacheConfig {
25    /// Maximum number of key-value pairs the cache can hold
26    capacity: NonZeroUsize,
27
28    /// Initial global age value
29    initial_age: usize,
30}
31
32impl LfudaCacheConfig {
33    /// Creates a new configuration for an LFUDA cache with initial age of 0.
34    ///
35    /// # Arguments
36    /// * `capacity` - Maximum number of key-value pairs the cache can hold
37    pub fn new(capacity: NonZeroUsize) -> Self {
38        Self {
39            capacity,
40            initial_age: 0,
41        }
42    }
43
44    /// Creates a new configuration for an LFUDA cache with a specific initial age.
45    ///
46    /// # Arguments
47    /// * `capacity` - Maximum number of key-value pairs the cache can hold
48    /// * `initial_age` - Initial global age value
49    pub fn with_initial_age(capacity: NonZeroUsize, initial_age: usize) -> Self {
50        Self {
51            capacity,
52            initial_age,
53        }
54    }
55
56    /// Returns the maximum number of key-value pairs the cache can hold.
57    pub fn capacity(&self) -> NonZeroUsize {
58        self.capacity
59    }
60
61    /// Returns the initial global age value.
62    pub fn initial_age(&self) -> usize {
63        self.initial_age
64    }
65}
66
67impl fmt::Debug for LfudaCacheConfig {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("LfudaCacheConfig")
70            .field("capacity", &self.capacity)
71            .field("initial_age", &self.initial_age)
72            .finish()
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn test_lfuda_config_creation() {
82        let config = LfudaCacheConfig::new(NonZeroUsize::new(100).unwrap());
83        assert_eq!(config.capacity().get(), 100);
84        assert_eq!(config.initial_age(), 0);
85
86        let config_with_age =
87            LfudaCacheConfig::with_initial_age(NonZeroUsize::new(50).unwrap(), 10);
88        assert_eq!(config_with_age.capacity().get(), 50);
89        assert_eq!(config_with_age.initial_age(), 10);
90    }
91}