pub struct LfuCache<K, V, S = DefaultHashBuilder> { /* private fields */ }
Expand description
An implementation of a Least Frequently Used (LFU) cache.
The cache tracks the frequency of access for each item and evicts the least frequently used items when the cache reaches capacity. In case of a tie in frequency, the least recently used item among those with the same frequency is evicted.
§Examples
use cache_rs::lfu::LfuCache;
use core::num::NonZeroUsize;
// Create an LFU cache with capacity 3
let mut cache = LfuCache::new(NonZeroUsize::new(3).unwrap());
// Add some items
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);
// Access "a" multiple times to increase its frequency
assert_eq!(cache.get(&"a"), Some(&1));
assert_eq!(cache.get(&"a"), Some(&1));
// Add a new item, which will evict the least frequently used item
cache.put("d", 4);
assert_eq!(cache.get(&"b"), None); // "b" was evicted as it had frequency 0
Implementations§
Source§impl<K: Hash + Eq, V: Clone, S: BuildHasher> LfuCache<K, V, S>
impl<K: Hash + Eq, V: Clone, S: BuildHasher> LfuCache<K, V, S>
Sourcepub fn with_hasher(cap: NonZeroUsize, hash_builder: S) -> Self
pub fn with_hasher(cap: NonZeroUsize, hash_builder: S) -> Self
Creates a new LFU cache with the specified capacity and hash builder.
§Examples
use cache_rs::lfu::LfuCache;
use core::num::NonZeroUsize;
use std::collections::hash_map::RandomState;
let cache: LfuCache<&str, u32, _> = LfuCache::with_hasher(
NonZeroUsize::new(10).unwrap(),
RandomState::new()
);
Sourcepub fn cap(&self) -> NonZeroUsize
pub fn cap(&self) -> NonZeroUsize
Returns the maximum number of key-value pairs the cache can hold.
Sourcepub fn put(&mut self, key: K, value: V) -> Option<(K, V)>where
K: Clone,
pub fn put(&mut self, key: K, value: V) -> Option<(K, V)>where
K: Clone,
Inserts a key-value pair into the cache.
If the cache already contained this key, the old value is replaced and returned. Otherwise, if the cache is at capacity, the least frequently used item is evicted. In case of a tie in frequency, the least recently used item among those with the same frequency is evicted.
New items are inserted with a frequency of 1.
Sourcepub fn record_miss(&mut self, object_size: u64)
pub fn record_miss(&mut self, object_size: u64)
Records a cache miss for metrics tracking (to be called by simulation system)
Source§impl<K: Hash + Eq, V> LfuCache<K, V>where
V: Clone,
impl<K: Hash + Eq, V> LfuCache<K, V>where
V: Clone,
Sourcepub fn new(cap: NonZeroUsize) -> LfuCache<K, V, DefaultHashBuilder>
pub fn new(cap: NonZeroUsize) -> LfuCache<K, V, DefaultHashBuilder>
Creates a new LFU cache with the specified capacity.
§Examples
use cache_rs::lfu::LfuCache;
use core::num::NonZeroUsize;
let cache: LfuCache<&str, u32> = LfuCache::new(NonZeroUsize::new(10).unwrap());