use std::collections::BTreeMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
pub const CACHE_FILE: &str = ".tomoxide_chunk_cache";
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Entry {
pub chunk: usize,
pub nx: usize,
pub nproj: usize,
pub nz: usize,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ChunkCache {
#[serde(default)]
entries: BTreeMap<String, Entry>,
}
pub fn key(file: &Path, algorithm: &str, dtype: &str, gpu: &str) -> String {
let f = std::fs::canonicalize(file)
.map(|p| p.display().to_string())
.unwrap_or_else(|_| file.display().to_string());
format!("{f}|{algorithm}|{dtype}|{gpu}")
}
impl ChunkCache {
pub fn load() -> Self {
match std::fs::read_to_string(CACHE_FILE) {
Ok(text) => toml::from_str(&text).unwrap_or_default(),
Err(_) => Self::default(),
}
}
pub fn get(&self, key: &str, nx: usize, nproj: usize, nz: usize) -> Option<usize> {
let e = self.entries.get(key)?;
(e.nx == nx && e.nproj == nproj && e.nz == nz).then_some(e.chunk)
}
pub fn insert(&mut self, key: String, entry: Entry) {
self.entries.insert(key, entry);
}
pub fn save(&self) -> anyhow::Result<()> {
std::fs::write(CACHE_FILE, toml::to_string_pretty(self)?)?;
Ok(())
}
}