Skip to main content

lockdocs_core/
cache.rs

1//! On-disk cache location and a stable hash for cache keys.
2
3use std::path::PathBuf;
4
5/// `LOCKDOCS_CACHE`, else the OS cache directory, else a temp dir.
6pub fn dir() -> PathBuf {
7    mcp_kit::cache::root("LOCKDOCS_CACHE", "lockdocs", mcp_kit::cache::Fallback::Temp, mcp_kit::cache::Override::NonEmpty).expect("temporary cache fallback")
8}
9
10/// FNV-1a 64: stable across builds and platforms.
11pub fn hash(parts: &[&str]) -> String {
12    let mut h: u64 = 0xcbf29ce484222325;
13    for p in parts {
14        for b in p.as_bytes().iter().chain(std::iter::once(&0u8)) {
15            h ^= *b as u64;
16            h = h.wrapping_mul(0x100000001b3);
17        }
18    }
19    format!("{h:016x}")
20}
21
22/// Total bytes and file count under the cache directory.
23pub fn usage() -> (u64, usize) {
24    fn walk(p: &std::path::Path, acc: &mut (u64, usize)) {
25        if let Ok(rd) = std::fs::read_dir(p) {
26            for e in rd.flatten() {
27                match e.file_type() {
28                    Ok(t) if t.is_dir() => walk(&e.path(), acc),
29                    Ok(_) => {
30                        acc.0 += e.metadata().map(|m| m.len()).unwrap_or(0);
31                        acc.1 += 1;
32                    }
33                    _ => {}
34                }
35            }
36        }
37    }
38    let mut acc = (0, 0);
39    walk(&dir(), &mut acc);
40    acc
41}