pub struct LruCache<K, V> { /* private fields */ }Expand description
A fixed-capacity, in-memory least-recently-used (LRU) cache.
When the cache is full, inserting a new entry evicts the entry that was least recently accessed. Updating an existing key moves it to the most-recently-used position without consuming extra capacity.
LruCache is not Sync; wrap it in std::sync::RwLock or
std::sync::Mutex when sharing across threads.
§Type parameters
§Examples
use std::num::NonZeroUsize;
use modo::cache::LruCache;
let mut cache: LruCache<&str, u32> = LruCache::new(NonZeroUsize::new(2).unwrap());
cache.put("a", 1);
cache.put("b", 2);
assert_eq!(cache.get(&"a"), Some(&1));
// Inserting a third entry evicts "b" (least recently used).
cache.put("c", 3);
assert!(cache.get(&"b").is_none());Implementations§
Source§impl<K: Eq + Hash + Clone, V> LruCache<K, V>
impl<K: Eq + Hash + Clone, V> LruCache<K, V>
Sourcepub fn new(capacity: NonZeroUsize) -> Self
pub fn new(capacity: NonZeroUsize) -> Self
Creates a new LruCache with the given maximum capacity.
The cache will hold at most capacity entries at any time. When a new
entry is inserted into a full cache, the least-recently-used entry is
evicted first.
Sourcepub fn get(&mut self, key: &K) -> Option<&V>
pub fn get(&mut self, key: &K) -> Option<&V>
Returns a reference to the value associated with key, or None if
the key is not present.
Accessing a key moves it to the most-recently-used position, making it the last candidate for eviction.
Sourcepub fn put(&mut self, key: K, value: V)
pub fn put(&mut self, key: K, value: V)
Inserts or updates the entry for key with the given value.
- If
keyalready exists, its value is replaced and it moves to the most-recently-used position. - If the cache is at capacity and
keyis new, the least-recently-used entry is evicted before the new entry is inserted.