pub struct LruCache<K, V> { /* private fields */ }Available on crate feature
std only.Expand description
A bounded, thread-safe LRU cache.
On insert overflow the least-recently-accessed entry is evicted. Both
get and insert count as accesses and
promote the affected entry to most-recently-used.
This is the reference implementation: correct, &self-everywhere,
Mutex-guarded. A lock-free, arena-backed implementation lands in a
later minor without changing this public surface.
§Example
use cache_mod::{Cache, LruCache};
let cache: LruCache<u32, &'static str> = LruCache::new(2).expect("capacity > 0");
cache.insert(1, "one");
cache.insert(2, "two");
assert_eq!(cache.get(&1), Some("one")); // 1 is now MRU, 2 is LRU
cache.insert(3, "three"); // evicts 2
assert_eq!(cache.get(&2), None);
assert_eq!(cache.get(&1), Some("one"));
assert_eq!(cache.get(&3), Some("three"));Implementations§
Source§impl<K, V> LruCache<K, V>
impl<K, V> LruCache<K, V>
Sourcepub fn new(capacity: usize) -> Result<Self, CacheError>
pub fn new(capacity: usize) -> Result<Self, CacheError>
Creates a cache with the given capacity.
Returns CacheError::InvalidCapacity if capacity == 0.
§Example
use cache_mod::LruCache;
let cache: LruCache<String, u32> = LruCache::new(128).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::LruCache;
let cap = NonZeroUsize::new(64).expect("64 != 0");
let cache: LruCache<String, u32> = LruCache::with_capacity(cap);Trait Implementations§
Source§impl<K, V> Cache<K, V> for LruCache<K, V>
impl<K, V> Cache<K, V> for LruCache<K, V>
Source§fn get(&self, key: &K) -> Option<V>
fn get(&self, key: &K) -> Option<V>
Returns the value associated with
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>
Removes the entry for
key and returns the value if present.Source§fn contains_key(&self, key: &K) -> bool
fn contains_key(&self, key: &K) -> bool
Auto Trait Implementations§
impl<K, V> !Freeze for LruCache<K, V>
impl<K, V> RefUnwindSafe for LruCache<K, V>
impl<K, V> Send for LruCache<K, V>
impl<K, V> Sync for LruCache<K, V>
impl<K, V> Unpin for LruCache<K, V>
impl<K, V> UnsafeUnpin for LruCache<K, V>
impl<K, V> UnwindSafe for LruCache<K, V>
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