use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize;
use std::sync::Mutex;
use lru::LruCache;
const NUM_SHARDS: usize = 64;
#[inline]
fn shard_index<K: Hash>(key: &K) -> usize {
struct FnvHasher(u64);
impl Hasher for FnvHasher {
#[inline]
fn finish(&self) -> u64 {
self.0
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 ^= b as u64;
self.0 = self.0.wrapping_mul(0x0000_0100_0000_01B3);
}
}
}
let mut h = FnvHasher(0xCBF2_9CE4_8422_2325);
key.hash(&mut h);
let hash = h.finish();
((hash ^ (hash >> 32)) as usize) & (NUM_SHARDS - 1)
}
pub struct ShardedLruCache<K, V> {
shards: [Mutex<LruCache<K, V>>; NUM_SHARDS],
}
impl<K: Hash + Eq, V: Clone> ShardedLruCache<K, V> {
pub fn new(total_capacity: usize) -> Self {
let per_shard = total_capacity.div_ceil(NUM_SHARDS).max(1);
let cap = NonZeroUsize::new(per_shard).unwrap();
let shards = std::array::from_fn(|_| Mutex::new(LruCache::new(cap)));
Self { shards }
}
#[inline]
pub fn get(&self, key: &K) -> Option<V> {
let idx = shard_index(key);
let mut guard = self.shards[idx].lock().expect("sharded lru lock poisoned");
guard.get(key).cloned()
}
#[inline]
pub fn put(&self, key: K, val: V) {
let idx = shard_index(&key);
let mut guard = self.shards[idx].lock().expect("sharded lru lock poisoned");
guard.put(key, val);
}
pub fn clear(&self) {
for shard in &self.shards {
shard.lock().expect("sharded lru lock poisoned").clear();
}
}
}