use std::collections::{HashMap, HashSet};
use plushie_core::protocol::TreeNode;
#[derive(Default)]
pub(crate) struct MemoCache {
entries: HashMap<String, (u64, Vec<TreeNode>)>,
live_this_cycle: HashSet<String>,
}
impl MemoCache {
pub fn new() -> Self {
Self::default()
}
pub fn begin_cycle(&mut self) {
self.live_this_cycle.clear();
}
pub fn mark_live(&mut self, scoped_id: &str) {
self.live_this_cycle.insert(scoped_id.to_string());
}
pub fn finish_cycle(&mut self) {
self.entries
.retain(|id, _| self.live_this_cycle.contains(id));
}
pub fn get(&self, scoped_id: &str, deps_hash: u64) -> Option<&[TreeNode]> {
let (stored_hash, cached) = self.entries.get(scoped_id)?;
if *stored_hash == deps_hash {
Some(cached.as_slice())
} else {
None
}
}
pub fn insert(&mut self, scoped_id: String, deps_hash: u64, children: Vec<TreeNode>) {
self.entries.insert(scoped_id, (deps_hash, children));
}
}