Skip to main content

coip_reader/
cache.rs

1//! Lock-sharded concurrent LRU cache for high-throughput multi-threaded reads.
2
3use std::hash::{Hash, Hasher};
4use std::num::NonZeroUsize;
5use std::sync::Mutex;
6
7use lru::LruCache;
8
9const NUM_SHARDS: usize = 64;
10
11/// Fast non-cryptographic FNV-1a hasher for shard selection.
12#[inline]
13fn shard_index<K: Hash>(key: &K) -> usize {
14    struct FnvHasher(u64);
15    impl Hasher for FnvHasher {
16        #[inline]
17        fn finish(&self) -> u64 {
18            self.0
19        }
20        #[inline]
21        fn write(&mut self, bytes: &[u8]) {
22            for &b in bytes {
23                self.0 ^= b as u64;
24                self.0 = self.0.wrapping_mul(0x0000_0100_0000_01B3);
25            }
26        }
27    }
28    let mut h = FnvHasher(0xCBF2_9CE4_8422_2325);
29    key.hash(&mut h);
30    let hash = h.finish();
31    // Mix upper and lower bits before masking
32    ((hash ^ (hash >> 32)) as usize) & (NUM_SHARDS - 1)
33}
34
35/// 16-shard thread-safe LRU cache with minimal lock contention under multi-core workloads.
36pub struct ShardedLruCache<K, V> {
37    shards: [Mutex<LruCache<K, V>>; NUM_SHARDS],
38}
39
40impl<K: Hash + Eq, V: Clone> ShardedLruCache<K, V> {
41    pub fn new(total_capacity: usize) -> Self {
42        let per_shard = total_capacity.div_ceil(NUM_SHARDS).max(1);
43        let cap = NonZeroUsize::new(per_shard).unwrap();
44        let shards = std::array::from_fn(|_| Mutex::new(LruCache::new(cap)));
45        Self { shards }
46    }
47
48    #[inline]
49    pub fn get(&self, key: &K) -> Option<V> {
50        let idx = shard_index(key);
51        let mut guard = self.shards[idx].lock().expect("sharded lru lock poisoned");
52        guard.get(key).cloned()
53    }
54
55    #[inline]
56    pub fn put(&self, key: K, val: V) {
57        let idx = shard_index(&key);
58        let mut guard = self.shards[idx].lock().expect("sharded lru lock poisoned");
59        guard.put(key, val);
60    }
61
62    pub fn clear(&self) {
63        for shard in &self.shards {
64            shard.lock().expect("sharded lru lock poisoned").clear();
65        }
66    }
67}