use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::rc::Rc;
#[derive(Clone, Default)]
pub(crate) struct ParseCache(HashMap<PathBuf, Rc<syn::File>>);
impl ParseCache {
#[must_use]
pub(crate) fn new() -> Self {
Self(HashMap::new())
}
#[must_use]
pub(crate) fn get(&self, path: &Path) -> Option<Rc<syn::File>> {
self.0.get(path).map(Rc::clone)
}
pub(crate) fn insert(&mut self, path: PathBuf, file: Rc<syn::File>) {
self.0.insert(path, file);
}
#[must_use]
pub(crate) fn len(&self) -> usize {
self.0.len()
}
#[must_use]
#[allow(dead_code)]
pub(crate) fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub(crate) fn get_or_parse<E, F>(
&mut self,
path: &Path,
read_and_parse: F,
) -> Result<Rc<syn::File>, E>
where
F: FnOnce(&Path) -> Result<syn::File, E>,
{
if let Some(cached) = self.0.get(path) {
return Ok(Rc::clone(cached));
}
let file = read_and_parse(path)?;
let rc = Rc::new(file);
self.0.insert(path.to_path_buf(), Rc::clone(&rc));
Ok(rc)
}
}