chalk_recursive/fixed_point/
cache.rs

1use rustc_hash::FxHashMap;
2use std::fmt::Debug;
3use std::hash::Hash;
4use std::sync::{Arc, Mutex};
5use tracing::debug;
6use tracing::instrument;
7/// The "cache" stores results for goals that we have completely solved.
8/// Things are added to the cache when we have completely processed their
9/// result, and it can be shared amongst many solvers.
10pub struct Cache<K, V>
11where
12    K: Hash + Eq + Debug,
13    V: Debug + Clone,
14{
15    data: Arc<Mutex<CacheData<K, V>>>,
16}
17struct CacheData<K, V>
18where
19    K: Hash + Eq + Debug,
20    V: Debug + Clone,
21{
22    cache: FxHashMap<K, V>,
23}
24
25impl<K, V> Cache<K, V>
26where
27    K: Hash + Eq + Debug,
28    V: Debug + Clone,
29{
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    /// Record a cache result.
35    #[instrument(skip(self))]
36    pub fn insert(&self, goal: K, result: V) {
37        let mut data = self.data.lock().unwrap();
38        data.cache.insert(goal, result);
39    }
40
41    /// Record a cache result.
42    pub fn get(&self, goal: &K) -> Option<V> {
43        let data = self.data.lock().unwrap();
44        if let Some(result) = data.cache.get(goal) {
45            debug!(?goal, ?result, "Cache hit");
46            Some(result.clone())
47        } else {
48            debug!(?goal, "Cache miss");
49            None
50        }
51    }
52}
53
54impl<K, V> Clone for Cache<K, V>
55where
56    K: Hash + Eq + Debug,
57    V: Debug + Clone,
58{
59    fn clone(&self) -> Self {
60        Self {
61            data: self.data.clone(),
62        }
63    }
64}
65
66impl<K, V> Default for Cache<K, V>
67where
68    K: Hash + Eq + Debug,
69    V: Debug + Clone,
70{
71    fn default() -> Self {
72        Self {
73            data: Default::default(),
74        }
75    }
76}
77
78impl<K, V> Default for CacheData<K, V>
79where
80    K: Hash + Eq + Debug,
81    V: Debug + Clone,
82{
83    fn default() -> Self {
84        Self {
85            cache: Default::default(),
86        }
87    }
88}