]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_query_system/src/cache.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / compiler / rustc_query_system / src / cache.rs
1 //! Cache for candidate selection.
2
3 use crate::dep_graph::{DepContext, DepNodeIndex};
4
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::sync::Lock;
7
8 use std::hash::Hash;
9
10 #[derive(Clone)]
11 pub struct Cache<Key, Value> {
12 hashmap: Lock<FxHashMap<Key, WithDepNode<Value>>>,
13 }
14
15 impl<Key, Value> Default for Cache<Key, Value> {
16 fn default() -> Self {
17 Self { hashmap: Default::default() }
18 }
19 }
20
21 impl<Key, Value> Cache<Key, Value> {
22 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
23 pub fn clear(&self) {
24 *self.hashmap.borrow_mut() = Default::default();
25 }
26 }
27
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))
31 }
32
33 pub fn insert(&self, key: Key, dep_node: DepNodeIndex, value: Value) {
34 self.hashmap.borrow_mut().insert(key, WithDepNode::new(dep_node, value));
35 }
36 }
37
38 #[derive(Clone, Eq, PartialEq)]
39 pub struct WithDepNode<T> {
40 dep_node: DepNodeIndex,
41 cached_value: T,
42 }
43
44 impl<T: Clone> WithDepNode<T> {
45 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
46 WithDepNode { dep_node, cached_value }
47 }
48
49 pub fn get<Tcx: DepContext>(&self, tcx: Tcx) -> T {
50 tcx.dep_graph().read_index(self.dep_node);
51 self.cached_value.clone()
52 }
53 }