1 //! Cache for candidate selection.
3 use crate::dep_graph::{DepContext, DepNodeIndex};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::sync::Lock;
11 pub struct Cache<Key, Value> {
12 hashmap: Lock<FxHashMap<Key, WithDepNode<Value>>>,
15 impl<Key, Value> Default for Cache<Key, Value> {
16 fn default() -> Self {
17 Self { hashmap: Default::default() }
21 impl<Key, Value> Cache<Key, Value> {
22 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
24 *self.hashmap.borrow_mut() = Default::default();
28 impl<Key: Eq + Hash, Value: Clone> Cache<Key, Value> {
29 pub fn get<Tcx: DepContext>(&self, key: &Key, tcx: Tcx) -> Option<Value> {
30 Some(self.hashmap.borrow().get(key)?.get(tcx))
33 pub fn insert(&self, key: Key, dep_node: DepNodeIndex, value: Value) {
34 self.hashmap.borrow_mut().insert(key, WithDepNode::new(dep_node, value));
38 #[derive(Clone, Eq, PartialEq)]
39 pub struct WithDepNode<T> {
40 dep_node: DepNodeIndex,
44 impl<T: Clone> WithDepNode<T> {
45 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
46 WithDepNode { dep_node, cached_value }
49 pub fn get<Tcx: DepContext>(&self, tcx: Tcx) -> T {
50 tcx.dep_graph().read_index(self.dep_node);
51 self.cached_value.clone()