]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/intern.rs
Rollup merge of #105141 - ohno418:fix-ice-on-invalid-var-decl-in-macro-call, r=compil...
[rust.git] / compiler / rustc_data_structures / src / intern.rs
1 use crate::stable_hasher::{HashStable, StableHasher};
2 use std::cmp::Ordering;
3 use std::hash::{Hash, Hasher};
4 use std::ops::Deref;
5 use std::ptr;
6
7 use crate::fingerprint::Fingerprint;
8
9 mod private {
10     #[derive(Clone, Copy, Debug)]
11     pub struct PrivateZst;
12 }
13
14 /// A reference to a value that is interned, and is known to be unique.
15 ///
16 /// Note that it is possible to have a `T` and a `Interned<T>` that are (or
17 /// refer to) equal but different values. But if you have two different
18 /// `Interned<T>`s, they both refer to the same value, at a single location in
19 /// memory. This means that equality and hashing can be done on the value's
20 /// address rather than the value's contents, which can improve performance.
21 ///
22 /// The `PrivateZst` field means you can pattern match with `Interned(v, _)`
23 /// but you can only construct a `Interned` with `new_unchecked`, and not
24 /// directly.
25 #[derive(Debug)]
26 #[rustc_pass_by_value]
27 pub struct Interned<'a, T>(pub &'a T, pub private::PrivateZst);
28
29 impl<'a, T> Interned<'a, T> {
30     /// Create a new `Interned` value. The value referred to *must* be interned
31     /// and thus be unique, and it *must* remain unique in the future. This
32     /// function has `_unchecked` in the name but is not `unsafe`, because if
33     /// the uniqueness condition is violated condition it will cause incorrect
34     /// behaviour but will not affect memory safety.
35     #[inline]
36     pub const fn new_unchecked(t: &'a T) -> Self {
37         Interned(t, private::PrivateZst)
38     }
39 }
40
41 impl<'a, T> Clone for Interned<'a, T> {
42     fn clone(&self) -> Self {
43         *self
44     }
45 }
46
47 impl<'a, T> Copy for Interned<'a, T> {}
48
49 impl<'a, T> Deref for Interned<'a, T> {
50     type Target = T;
51
52     #[inline]
53     fn deref(&self) -> &T {
54         self.0
55     }
56 }
57
58 impl<'a, T> PartialEq for Interned<'a, T> {
59     #[inline]
60     fn eq(&self, other: &Self) -> bool {
61         // Pointer equality implies equality, due to the uniqueness constraint.
62         ptr::eq(self.0, other.0)
63     }
64 }
65
66 impl<'a, T> Eq for Interned<'a, T> {}
67
68 impl<'a, T: PartialOrd> PartialOrd for Interned<'a, T> {
69     fn partial_cmp(&self, other: &Interned<'a, T>) -> Option<Ordering> {
70         // Pointer equality implies equality, due to the uniqueness constraint,
71         // but the contents must be compared otherwise.
72         if ptr::eq(self.0, other.0) {
73             Some(Ordering::Equal)
74         } else {
75             let res = self.0.partial_cmp(other.0);
76             debug_assert_ne!(res, Some(Ordering::Equal));
77             res
78         }
79     }
80 }
81
82 impl<'a, T: Ord> Ord for Interned<'a, T> {
83     fn cmp(&self, other: &Interned<'a, T>) -> Ordering {
84         // Pointer equality implies equality, due to the uniqueness constraint,
85         // but the contents must be compared otherwise.
86         if ptr::eq(self.0, other.0) {
87             Ordering::Equal
88         } else {
89             let res = self.0.cmp(other.0);
90             debug_assert_ne!(res, Ordering::Equal);
91             res
92         }
93     }
94 }
95
96 impl<'a, T> Hash for Interned<'a, T> {
97     #[inline]
98     fn hash<H: Hasher>(&self, s: &mut H) {
99         // Pointer hashing is sufficient, due to the uniqueness constraint.
100         ptr::hash(self.0, s)
101     }
102 }
103
104 impl<T, CTX> HashStable<CTX> for Interned<'_, T>
105 where
106     T: HashStable<CTX>,
107 {
108     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
109         self.0.hash_stable(hcx, hasher);
110     }
111 }
112
113 /// A helper type that you can wrap round your own type in order to automatically
114 /// cache the stable hash on creation and not recompute it whenever the stable hash
115 /// of the type is computed.
116 /// This is only done in incremental mode. You can also opt out of caching by using
117 /// StableHash::ZERO for the hash, in which case the hash gets computed each time.
118 /// This is useful if you have values that you intern but never (can?) use for stable
119 /// hashing.
120 #[derive(Copy, Clone)]
121 pub struct WithStableHash<T> {
122     pub internee: T,
123     pub stable_hash: Fingerprint,
124 }
125
126 impl<T: PartialEq> PartialEq for WithStableHash<T> {
127     #[inline]
128     fn eq(&self, other: &Self) -> bool {
129         self.internee.eq(&other.internee)
130     }
131 }
132
133 impl<T: Eq> Eq for WithStableHash<T> {}
134
135 impl<T: Ord> PartialOrd for WithStableHash<T> {
136     fn partial_cmp(&self, other: &WithStableHash<T>) -> Option<Ordering> {
137         Some(self.internee.cmp(&other.internee))
138     }
139 }
140
141 impl<T: Ord> Ord for WithStableHash<T> {
142     fn cmp(&self, other: &WithStableHash<T>) -> Ordering {
143         self.internee.cmp(&other.internee)
144     }
145 }
146
147 impl<T> Deref for WithStableHash<T> {
148     type Target = T;
149
150     #[inline]
151     fn deref(&self) -> &T {
152         &self.internee
153     }
154 }
155
156 impl<T: Hash> Hash for WithStableHash<T> {
157     #[inline]
158     fn hash<H: Hasher>(&self, s: &mut H) {
159         if self.stable_hash != Fingerprint::ZERO {
160             self.stable_hash.hash(s)
161         } else {
162             self.internee.hash(s)
163         }
164     }
165 }
166
167 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for WithStableHash<T> {
168     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
169         if self.stable_hash == Fingerprint::ZERO || cfg!(debug_assertions) {
170             // No cached hash available. This can only mean that incremental is disabled.
171             // We don't cache stable hashes in non-incremental mode, because they are used
172             // so rarely that the performance actually suffers.
173
174             // We need to build the hash as if we cached it and then hash that hash, as
175             // otherwise the hashes will differ between cached and non-cached mode.
176             let stable_hash: Fingerprint = {
177                 let mut hasher = StableHasher::new();
178                 self.internee.hash_stable(hcx, &mut hasher);
179                 hasher.finish()
180             };
181             if cfg!(debug_assertions) && self.stable_hash != Fingerprint::ZERO {
182                 assert_eq!(
183                     stable_hash, self.stable_hash,
184                     "cached stable hash does not match freshly computed stable hash"
185                 );
186             }
187             stable_hash.hash_stable(hcx, hasher);
188         } else {
189             self.stable_hash.hash_stable(hcx, hasher);
190         }
191     }
192 }
193
194 #[cfg(test)]
195 mod tests;