pub struct LruCache<K, V>{ /* private fields */ }Expand description
A fixed-capacity LRU cache.
The cache holds at most capacity entries. When a
put would exceed the capacity, the
least-recently-used entry is evicted. get updates
the recency so the just-read entry becomes the most-
recently-used.
All operations are O(1) amortized (put, get,
remove, contains) except iter, which is O(n).
§Capacity edge cases
capacity = 0- the cache accepts no entries. Bothputandgetbehave as no-ops (well,getstill evicts because there’s nothing to evict;putsilently drops the entry).capacity = 1- the cache holds exactly one entry. Everyputevicts the previous entry.
§Lombok New derivation
#[derive(New)] generates LruCache::new(capacity) —
the map and order fields are skipped with
#[new(skip)] so Lombok falls back to
<HashMap as Default>::default() and
<VecDeque as Default>::default() (which both call
new() internally), preserving the canonical
single-argument call site.
Implementations§
Source§impl<K, V> LruCache<K, V>
impl<K, V> LruCache<K, V>
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the current number of entries in the cache.
§Returns
usize- The number of items in the collection.
Sourcepub fn put(&mut self, key: K, value: V) -> Option<(K, V)>
pub fn put(&mut self, key: K, value: V) -> Option<(K, V)>
Inserts a key-value pair into the cache. If the key is already present, the existing value is replaced (and the entry becomes the most- recently-used). If the cache is at capacity and the key is new, the least-recently-used entry is evicted first.
Returns the evicted entry, if any.
§Arguments
K: Clone + Eq + Hash- A generic type parameter.V- AVparameter.
§Returns
Option<(K, V)>-Some(...)on success,Noneotherwise.
Sourcepub fn iter(&self) -> impl Iterator<Item = (&K, &V)>
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)>
Returns an iterator over the entries in most-recently-used-first order.
§Returns
impl Iterator<Item- Aimpl Iterator<Itemvalue.
Sourcepub fn keys(&self) -> impl Iterator<Item = &K>
pub fn keys(&self) -> impl Iterator<Item = &K>
Returns an iterator over the keys in most-recently-used-first order.
§Returns
impl Iterator<Item- Aimpl Iterator<Itemvalue.