coip-reader 0.1.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
Documentation
//! Lock-sharded concurrent LRU cache for high-throughput multi-threaded reads.

use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize;
use std::sync::Mutex;

use lru::LruCache;

const NUM_SHARDS: usize = 64;

/// Fast non-cryptographic FNV-1a hasher for shard selection.
#[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();
    // Mix upper and lower bits before masking
    ((hash ^ (hash >> 32)) as usize) & (NUM_SHARDS - 1)
}

/// 16-shard thread-safe LRU cache with minimal lock contention under multi-core workloads.
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();
        }
    }
}