pub struct TinyLfuCache<K, V> { /* private fields */ }std only.Expand description
A bounded, thread-safe cache with admission control.
TinyLfuCache tracks the access frequency of every key it observes —
including keys that aren’t (yet) in the cache — using a fixed-size
Count-Min Sketch. On capacity overflow, an incoming key is
admitted only if its estimated frequency exceeds the LRU victim’s.
One-hit-wonders are rejected at the door instead of evicting hot entries.
This is a deliberate semantic deviation from LruCache / LfuCache /
TtlCache: a successful insert call does not
guarantee that the value is in the cache. The admission filter may
have rejected it. Callers that need strict insertion guarantees should
use LruCache or LfuCache instead.
0.6.0 implementation:
- main cache is arena-backed (O(1) promote, O(1) evict — same shape as
LruCache) - depth-4 Count-Min Sketch with
u8saturating counters - width =
max(MIN_SKETCH_WIDTH, 2 × capacity), rounded to the next power of two - periodic frequency decay: every
10 × capacityincrements, every counter is right-shifted by 1 (W-TinyLFU “aging” step, keeps the sketch responsive to shifting workloads) - main cache uses LRU ordering; eviction victim = least-recently-accessed
- lock-minimized via
&self+Mutex<Inner>; a sharded / lock-free variant lands in 0.7.0 without changing this public surface
§Example
use cache_mod::{Cache, TinyLfuCache};
let cache: TinyLfuCache<&'static str, u32> =
TinyLfuCache::new(4).expect("capacity > 0");
// Build up the frequency signal for "hot".
for _ in 0..16 {
let _ = cache.get(&"hot");
let _ = cache.insert("hot", 1);
}
// A subsequent insert will see "hot" as warm in the sketch.
assert_eq!(cache.get(&"hot"), Some(1));Implementations§
Source§impl<K, V> TinyLfuCache<K, V>
impl<K, V> TinyLfuCache<K, V>
Sourcepub fn new(capacity: usize) -> Result<Self, CacheError>
pub fn new(capacity: usize) -> Result<Self, CacheError>
Creates a cache with the given entry-count capacity.
Returns CacheError::InvalidCapacity if capacity == 0.
§Example
use cache_mod::TinyLfuCache;
let cache: TinyLfuCache<String, u32> =
TinyLfuCache::new(256).expect("capacity > 0");Sourcepub fn with_capacity(capacity: NonZeroUsize) -> Self
pub fn with_capacity(capacity: NonZeroUsize) -> Self
Creates a cache with the given non-zero capacity. Infallible.
§Example
use std::num::NonZeroUsize;
use cache_mod::TinyLfuCache;
let cap = NonZeroUsize::new(256).expect("256 != 0");
let cache: TinyLfuCache<String, u32> = TinyLfuCache::with_capacity(cap);Trait Implementations§
Source§impl<K, V> Cache<K, V> for TinyLfuCache<K, V>
impl<K, V> Cache<K, V> for TinyLfuCache<K, V>
Source§fn get(&self, key: &K) -> Option<V>
fn get(&self, key: &K) -> Option<V>
key, if any, and counts as an
access for the purposes of the eviction policy.Source§fn remove(&self, key: &K) -> Option<V>
fn remove(&self, key: &K) -> Option<V>
key and returns the value if present.