evictor
Provides several cache implementations with different eviction policies:
- LRU (Least Recently Used) - Evicts the item that was accessed longest ago
- MRU (Most Recently Used) - Evicts the item that was accessed most recently
- LFU (Least Frequently Used) - Evicts the item that has been accessed least frequently
All caches are generic over key and value types, with a configurable capacity.
Usage
LRU (Least Recently Used) Cache
Evicts the item that was accessed longest ago:
use NonZeroUsize;
use Lru;
let mut cache = new;
cache.insert;
cache.insert;
cache.insert;
// Access entry (marks as recently used)
cache.get;
// Insert when full evicts least recently used
cache.insert;
assert!; // 2 was evicted (least recently used)
assert!; // 1 was recently accessed, so kept
MRU (Most Recently Used) Cache
Evicts the item that was accessed most recently:
use NonZeroUsize;
use Mru;
let mut cache = new;
cache.insert;
cache.insert;
cache.insert;
// Access entry (marks as recently used)
cache.get;
// Insert when full evicts most recently used
cache.insert;
assert!; // 1 was evicted (most recently used)
assert!; // 2 was not recently accessed, so kept
LFU (Least Frequently Used) Cache
Evicts the item that has been accessed least frequently:
use NonZeroUsize;
use Lfu;
let mut cache = new;
cache.insert;
cache.insert;
cache.insert;
// Access entries different numbers of times
cache.get; // frequency: 1
cache.get; // frequency: 2
cache.get; // frequency: 1
// Key 3 has frequency: 0 (never accessed after insertion)
// Insert when full evicts least frequently used
cache.insert;
assert!; // 3 was evicted (frequency 0)
assert!; // 1 has highest frequency (2)
assert!; // 2 has frequency 1
Creating from Iterator
All cache types can be created from iterators. This will set the capacity to the number of items in the iterator:
use ;
let items = vec!;
// Works with any cache type
let lru_cache: = items.clone.into_iter.collect;
let mru_cache: = items.clone.into_iter.collect;
let lfu_cache: = items.into_iter.collect;
Common Operations
All cache types support the same operations with identical APIs:
use NonZeroUsize;
use Lru; // Could also use Mru or Lfu
let mut cache = new;
// Insert and access
cache.insert;
cache.insert;
let value = cache.get; // Returns Some(&String) and updates cache order
// Non-mutating operations (don't affect eviction order)
let value = cache.peek; // Returns Some(&String) without updating order
let exists = cache.contains_key; // Returns bool
if let Some = cache.tail
// Other operations
cache.remove; // Remove specific key
if let Some = cache.pop
cache.clear; // Remove all entries
Features
Default Features
ahash- Fast hashing using theahashcrate (enabled by default)
License
This project is licensed under the either the APACHE or MIT License at your option. See the LICENSE-APACHE and LICENSE-MIT files for details.