use parking_lot::RwLock;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
#[derive(Debug, Default)]
pub struct FileCache {
line_cache: RwLock<HashMap<String, Vec<String>>>,
raw_cache: RwLock<HashMap<String, String>>,
}
impl FileCache {
pub fn new() -> Self {
Self::default()
}
pub fn get_lines(&self, path: &str) -> anyhow::Result<Vec<String>> {
{
let cache = self.line_cache.read();
if let Some(lines) = cache.get(path) {
return Ok(lines.clone());
}
}
let mut cache = self.line_cache.write();
if let Some(lines) = cache.get(path) {
return Ok(lines.clone());
}
let content = fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("failed to read file '{}': {}", path, e))?;
let lines: Vec<String> = content
.lines()
.filter(|l| !l.trim().is_empty())
.map(String::from)
.collect();
cache.insert(path.to_string(), lines.clone());
Ok(lines)
}
pub fn get_raw(&self, path: &str) -> anyhow::Result<String> {
{
let cache = self.raw_cache.read();
if let Some(content) = cache.get(path) {
return Ok(content.clone());
}
}
let mut cache = self.raw_cache.write();
if let Some(content) = cache.get(path) {
return Ok(content.clone());
}
let content = fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("failed to read file '{}': {}", path, e))?;
cache.insert(path.to_string(), content.clone());
Ok(content)
}
pub fn exists(&self, path: &str) -> bool {
Path::new(path).exists()
}
pub fn clear(&self) {
self.line_cache.write().clear();
self.raw_cache.write().clear();
}
}