bhandaar 0.1.0-alpha.1

On-disk LRU/TTL file cache for Rust with cross-process concurrency via flock(2)
Documentation
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, RwLock};

/// A shard holds a subset of cache entries with its own lock.
pub struct Shard {
    /// Lock for eviction coordination (exclusive access).
    lock: Mutex<()>,
    /// In-memory index: key → file path.
    entries: RwLock<HashMap<String, PathBuf>>,
}

impl Shard {
    /// Create a new empty shard.
    pub fn new() -> Self {
        Self {
            lock: Mutex::new(()),
            entries: RwLock::new(HashMap::new()),
        }
    }

    /// Assign a key to this shard (store the mapping).
    pub fn insert(&self, key: String, path: PathBuf) {
        let mut entries = self.entries.write().unwrap();
        entries.insert(key, path);
    }

    /// Atomically check if key exists and insert if absent.
    /// Returns true if inserted, false if key already existed.
    pub fn insert_if_absent(&self, key: String, path: PathBuf) -> bool {
        let mut entries = self.entries.write().unwrap();
        if entries.contains_key(&key) {
            false
        } else {
            entries.insert(key, path);
            true
        }
    }

    /// Remove a key from this shard.
    pub fn remove(&self, key: &str) -> Option<PathBuf> {
        let mut entries = self.entries.write().unwrap();
        entries.remove(key)
    }

    /// Get the file path for a key.
    pub fn get_path(&self, key: &str) -> Option<PathBuf> {
        let entries = self.entries.read().unwrap();
        entries.get(key).cloned()
    }

    /// Check if a key exists in this shard.
    pub fn contains(&self, key: &str) -> bool {
        let entries = self.entries.read().unwrap();
        entries.contains_key(key)
    }

    /// Get all keys and their paths in this shard.
    pub fn entries(&self) -> Vec<(String, PathBuf)> {
        let entries = self.entries.read().unwrap();
        entries.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
    }

    #[allow(dead_code)]
    /// Get the number of entries in this shard.
    pub fn len(&self) -> usize {
        let entries = self.entries.read().unwrap();
        entries.len()
    }

    #[allow(dead_code)]
    /// Check if the shard is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Lock the shard for exclusive access (e.g., during eviction).
    pub fn lock_exclusive(&self) -> std::sync::MutexGuard<'_, ()> {
        self.lock.lock().unwrap()
    }
}

impl Default for Shard {
    fn default() -> Self {
        Self::new()
    }
}

/// Assign a key to a shard index based on hash.
pub fn shard_index(key: &str, num_shards: usize) -> usize {
    let hash = {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        key.hash(&mut hasher);
        hasher.finish() as usize
    };
    hash % num_shards
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_shard_is_empty() {
        let shard = Shard::new();
        assert!(shard.is_empty());
        assert_eq!(shard.len(), 0);
    }

    #[test]
    fn insert_and_get() {
        let shard = Shard::new();
        shard.insert("key1".to_string(), PathBuf::from("/path/to/file"));
        assert!(shard.contains("key1"));
        assert_eq!(shard.get_path("key1"), Some(PathBuf::from("/path/to/file")));
    }

    #[test]
    fn remove_returns_path() {
        let shard = Shard::new();
        shard.insert("key1".to_string(), PathBuf::from("/path"));
        let removed = shard.remove("key1");
        assert_eq!(removed, Some(PathBuf::from("/path")));
        assert!(!shard.contains("key1"));
    }

    #[test]
    fn entries_returns_all() {
        let shard = Shard::new();
        shard.insert("a".to_string(), PathBuf::from("/a"));
        shard.insert("b".to_string(), PathBuf::from("/b"));
        let entries = shard.entries();
        assert_eq!(entries.len(), 2);
    }

    #[test]
    fn shard_index_deterministic() {
        let i1 = shard_index("key", 16);
        let i2 = shard_index("key", 16);
        assert_eq!(i1, i2);
    }

    #[test]
    fn shard_index_within_bounds() {
        for i in 0..100 {
            let key = format!("key-{}", i);
            let idx = shard_index(&key, 8);
            assert!(idx < 8);
        }
    }
}