pub struct ShardedLruCache<K, V>where
K: Clone + Debug + Hash + Eq + Send + Sync + 'static,
V: Clone + Debug + Send + Sync + 'static,{ /* private fields */ }Expand description
A sharded LRU cache implementation for high-concurrency scenarios.
This implementation divides the cache into multiple shards, each protected by its own mutex,
to reduce contention in concurrent access scenarios. The number of shards is automatically
determined based on the total capacity, but will not exceed MAX_SHARDS.
§Type Parameters
K- The type of keys used in the cache. Must implementClone + Debug + Hash + Eq + Send + Sync + 'staticV- The type of values stored in the cache. Must implementClone + Debug + Send + Sync + 'static
§Examples
use lrust_cache::ShardedLruCache;
let cache = ShardedLruCache::new(1000);
cache.put("key1".to_string(), "value1".to_string());
assert_eq!(cache.get(&"key1".to_string()), Some("value1".to_string()));Implementations§
Source§impl<K, V> ShardedLruCache<K, V>
impl<K, V> ShardedLruCache<K, V>
Sourcepub fn new(capacity: usize) -> Self
pub fn new(capacity: usize) -> Self
Creates a new sharded LRU cache with the specified total capacity.
The number of shards is automatically determined based on the capacity,
ensuring that each shard has at least MIN_SHARD_CAPACITY entries
and the total number of shards is a power of 2 not exceeding MAX_SHARDS.
§Arguments
capacity- The total capacity of the cache
§Panics
Panics if capacity is 0
Sourcepub fn num_shards(&self) -> usize
pub fn num_shards(&self) -> usize
Returns the number of shards in the cache.
Sourcepub fn put(&self, key: K, value: V) -> Option<V>
pub fn put(&self, key: K, value: V) -> Option<V>
Inserts a key-value pair into the cache.
If the key already exists, the value is updated and the old value is returned. If the cache is at capacity, the least recently used entry is removed to make space.
§Arguments
key- The key to insertvalue- The value to insert
§Returns
Some(V)if the key already existed (returns the old value)Noneif the key didn’t exist