agentic_reality/cache/
invalidation.rs1use std::collections::{HashMap, HashSet};
2use std::hash::Hash;
3
4pub struct CacheInvalidator<K> {
5 dependents: HashMap<K, HashSet<K>>,
6}
7impl<K: Eq + Hash + Clone> CacheInvalidator<K> {
8 pub fn new() -> Self {
9 Self {
10 dependents: HashMap::new(),
11 }
12 }
13 pub fn add_dependency(&mut self, dep: K, dependent: K) {
14 self.dependents.entry(dep).or_default().insert(dependent);
15 }
16 pub fn cascade(&self, key: &K) -> Vec<K> {
17 let mut result = Vec::new();
18 let mut visited = HashSet::new();
19 let mut stack = vec![key.clone()];
20 while let Some(current) = stack.pop() {
21 if !visited.insert(current.clone()) {
22 continue;
23 }
24 result.push(current.clone());
25 if let Some(deps) = self.dependents.get(¤t) {
26 for dep in deps {
27 if !visited.contains(dep) {
28 stack.push(dep.clone());
29 }
30 }
31 }
32 }
33 result
34 }
35 pub fn clear(&mut self) {
36 self.dependents.clear();
37 }
38}
39impl<K: Eq + Hash + Clone> Default for CacheInvalidator<K> {
40 fn default() -> Self {
41 Self::new()
42 }
43}