bhandaar 0.1.0-alpha.1

On-disk LRU/TTL file cache for Rust with cross-process concurrency via flock(2)
Documentation
use sha2::{Sha256, Digest};
use std::path::PathBuf;

/// Hash a key to a two-level directory path.
///
/// Uses SHA-256 truncated to 16 hex chars, split into:
/// - First 2 chars → top-level directory
/// - Next 2 chars → sub-directory
/// - Remaining 12 chars → filename prefix
///
/// Example: "my-key" → "a1/b2/c3d4e5f6g7h8"
pub fn hash_key(key: &str) -> PathBuf {
    let mut hasher = Sha256::new();
    hasher.update(key.as_bytes());
    let result = hasher.finalize();

    let hex = hex_encode(&result[..8]); // Use first 8 bytes (16 hex chars)

    let top = &hex[0..2];
    let mid = &hex[2..4];
    let filename = &hex[4..16];

    PathBuf::from(top).join(mid).join(filename)
}

/// Get the data file path for a hashed key.
pub fn data_path(key: &str) -> PathBuf {
    let hash = hash_key(key);
    let filename = format!("{}.dat", hash.file_stem().unwrap().to_str().unwrap());
    hash.parent().unwrap().join(filename)
}

/// Get the metadata file path for a hashed key.
pub fn meta_path(key: &str) -> PathBuf {
    let hash = hash_key(key);
    let filename = format!("{}.dat.meta", hash.file_stem().unwrap().to_str().unwrap());
    hash.parent().unwrap().join(filename)
}

/// Encode bytes to hex string.
fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

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

    #[test]
    fn hash_key_creates_two_level_path() {
        let path = hash_key("test-key");
        let components: Vec<_> = path.components().collect();
        assert_eq!(components.len(), 3); // top/mid/filename
    }

    #[test]
    fn hash_key_deterministic() {
        let path1 = hash_key("same-key");
        let path2 = hash_key("same-key");
        assert_eq!(path1, path2);
    }

    #[test]
    fn hash_key_different_for_different_keys() {
        let path1 = hash_key("key-1");
        let path2 = hash_key("key-2");
        assert_ne!(path1, path2);
    }

    #[test]
    fn data_path_has_dat_extension() {
        let path = data_path("my-key");
        assert!(path.to_str().unwrap().ends_with(".dat"));
    }

    #[test]
    fn meta_path_has_dat_meta_extension() {
        let path = meta_path("my-key");
        assert!(path.to_str().unwrap().ends_with(".dat.meta"));
    }

    #[test]
    fn paths_are_consistent() {
        let dp = data_path("key");
        let mp = meta_path("key");
        // Same parent directory
        assert_eq!(dp.parent(), mp.parent());
    }
}