pub struct LruCache<K, V, S = DefaultHashBuilder> { /* private fields */ }Expand description
An implementation of a Least Recently Used (LRU) cache.
The cache has a fixed capacity and supports O(1) operations for inserting, retrieving, and updating entries. When the cache reaches capacity, the least recently used entry will be evicted to make room for new entries.
§Examples
use cache_rs::LruCache;
use core::num::NonZeroUsize;
let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
// Add items to the cache
cache.put("apple", 1);
cache.put("banana", 2);
// Accessing items updates their recency
assert_eq!(cache.get(&"apple"), Some(&1));
// Adding beyond capacity evicts the least recently used item
cache.put("cherry", 3);
assert_eq!(cache.get(&"banana"), None);
assert_eq!(cache.get(&"apple"), Some(&1));
assert_eq!(cache.get(&"cherry"), Some(&3));Implementations§
Source§impl<K: Hash + Eq, V: Clone, S: BuildHasher> LruCache<K, V, S>
impl<K: Hash + Eq, V: Clone, S: BuildHasher> LruCache<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 LRU cache with the specified capacity and hash builder.
Sourcepub fn with_hasher_and_size(
cap: NonZeroUsize,
hash_builder: S,
max_size_bytes: u64,
) -> Self
pub fn with_hasher_and_size( cap: NonZeroUsize, hash_builder: S, max_size_bytes: u64, ) -> Self
Creates a new LRU cache with specified capacity, hash builder, and size limit.
pub fn cap(&self) -> NonZeroUsize
pub fn len(&self) -> usize
pub fn is_empty(&self) -> bool
pub fn get<Q>(&mut self, key: &Q) -> Option<&V>
pub fn record_miss(&mut self, object_size: u64)
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
Trait Implementations§
Source§impl<K: Hash + Eq, V: Clone, S: BuildHasher> CacheMetrics for LruCache<K, V, S>
impl<K: Hash + Eq, V: Clone, S: BuildHasher> CacheMetrics for LruCache<K, V, S>
Auto Trait Implementations§
impl<K, V, S> Freeze for LruCache<K, V, S>where
S: Freeze,
impl<K, V, S> RefUnwindSafe for LruCache<K, V, S>
impl<K, V, S> Send for LruCache<K, V, S>
impl<K, V, S> Sync for LruCache<K, V, S>
impl<K, V, S> Unpin for LruCache<K, V, S>
impl<K, V, S> UnwindSafe for LruCache<K, V, S>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more