rustc_query_system/
cache.rs1use std::hash::Hash;
4
5use rustc_data_structures::fx::FxHashMap;
6use rustc_data_structures::sync::Lock;
7
8use crate::dep_graph::{DepContext, DepNodeIndex};
9
10pub struct Cache<Key, Value> {
11 hashmap: Lock<FxHashMap<Key, WithDepNode<Value>>>,
12}
13
14impl<Key: Clone, Value: Clone> Clone for Cache<Key, Value> {
15 fn clone(&self) -> Self {
16 Self { hashmap: Lock::new(self.hashmap.borrow().clone()) }
17 }
18}
19
20impl<Key, Value> Default for Cache<Key, Value> {
21 fn default() -> Self {
22 Self { hashmap: Default::default() }
23 }
24}
25
26impl<Key: Eq + Hash, Value: Clone> Cache<Key, Value> {
27 pub fn get<Tcx: DepContext>(&self, key: &Key, tcx: Tcx) -> Option<Value> {
28 Some(self.hashmap.borrow().get(key)?.get(tcx))
29 }
30
31 pub fn insert(&self, key: Key, dep_node: DepNodeIndex, value: Value) {
32 self.hashmap.borrow_mut().insert(key, WithDepNode::new(dep_node, value));
33 }
34}
35
36#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for WithDepNode<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "WithDepNode",
"dep_node", &self.dep_node, "cached_value", &&self.cached_value)
}
}Debug, #[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for WithDepNode<T> {
#[inline]
fn clone(&self) -> WithDepNode<T> {
WithDepNode {
dep_node: ::core::clone::Clone::clone(&self.dep_node),
cached_value: ::core::clone::Clone::clone(&self.cached_value),
}
}
}Clone, #[automatically_derived]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for WithDepNode<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<DepNodeIndex>;
let _: ::core::cmp::AssertParamIsEq<T>;
}
}Eq, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for WithDepNode<T> {
#[inline]
fn eq(&self, other: &WithDepNode<T>) -> bool {
self.dep_node == other.dep_node &&
self.cached_value == other.cached_value
}
}PartialEq)]
37pub struct WithDepNode<T> {
38 dep_node: DepNodeIndex,
39 cached_value: T,
40}
41
42impl<T: Clone> WithDepNode<T> {
43 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
44 WithDepNode { dep_node, cached_value }
45 }
46
47 pub fn get<Tcx: DepContext>(&self, tcx: Tcx) -> T {
48 tcx.dep_graph().read_index(self.dep_node);
49 self.cached_value.clone()
50 }
51}