stable_hasher.rs - source (original) (raw)
rustc_data_structures/
stable_hasher.rs
1use std::hash::{BuildHasher, Hash, Hasher};
2use std:📑:PhantomData;
3use std::mem;
4use std::num::NonZero;
5
6use rustc_index::bit_set::{self, DenseBitSet};
7use rustc_index::{Idx, IndexSlice, IndexVec};
8use smallvec::SmallVec;
9
10#[cfg(test)]
11mod tests;
12
13use rustc_hashes::{Hash64, Hash128};
14pub use rustc_stable_hash::{
15 FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher,
16};
17
18/// Something that implements `HashStable<CTX>` can be hashed in a way that is
19/// stable across multiple compilation sessions.
20///
21/// Note that `HashStable` imposes rather more strict requirements than usual
22/// hash functions:
23///
24/// - Stable hashes are sometimes used as identifiers. Therefore they must
25/// conform to the corresponding `PartialEq` implementations:
26///
27/// - `x == y` implies `hash_stable(x) == hash_stable(y)`, and
28/// - `x != y` implies `hash_stable(x) != hash_stable(y)`.
29///
30/// That second condition is usually not required for hash functions
31/// (e.g. `Hash`). In practice this means that `hash_stable` must feed any
32/// information into the hasher that a `PartialEq` comparison takes into
33/// account. See [#49300](https://github.com/rust-lang/rust/issues/49300)
34/// for an example where violating this invariant has caused trouble in the
35/// past.
36///
37/// - `hash_stable()` must be independent of the current
38/// compilation session. E.g. they must not hash memory addresses or other
39/// things that are "randomly" assigned per compilation session.
40///
41/// - `hash_stable()` must be independent of the host architecture. The
42/// `StableHasher` takes care of endianness and `isize`/`usize` platform
43/// differences.
44pub trait HashStable<CTX> {
45 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher);
46}
47
48/// Implement this for types that can be turned into stable keys like, for
49/// example, for DefId that can be converted to a DefPathHash. This is used for
50/// bringing maps into a predictable order before hashing them.
51pub trait ToStableHashKey<HCX> {
52 type KeyType: Ord + Sized + HashStable<HCX>;
53 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
54}
55
56/// Trait for marking a type as having a sort order that is
57/// stable across compilation session boundaries. More formally:
58///
59/// ```txt
60/// Ord::cmp(a1, b1) == Ord::cmp(a2, b2)
61/// where a2 = decode(encode(a1, context1), context2)
62/// b2 = decode(encode(b1, context1), context2)
63/// ```
64///
65/// i.e. the result of `Ord::cmp` is not influenced by encoding
66/// the values in one session and then decoding them in another
67/// session.
68///
69/// This is trivially true for types where encoding and decoding
70/// don't change the bytes of the values that are used during
71/// comparison and comparison only depends on these bytes (as
72/// opposed to some non-local state). Examples are u32, String,
73/// Path, etc.
74///
75/// But it is not true for:
76/// - `*const T` and `*mut T` because the values of these pointers
77/// will change between sessions.
78/// - `DefIndex`, `CrateNum`, `LocalDefId`, because their concrete
79/// values depend on state that might be different between
80/// compilation sessions.
81///
82/// The associated constant `CAN_USE_UNSTABLE_SORT` denotes whether
83/// unstable sorting can be used for this type. Set to true if and
84/// only if `a == b` implies `a` and `b` are fully indistinguishable.
85pub trait StableOrd: Ord {
86 const CAN_USE_UNSTABLE_SORT: bool;
87
88 /// Marker to ensure that implementors have carefully considered
89 /// whether their `Ord` implementation obeys this trait's contract.
90 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: ();
91}
92
93impl<T: StableOrd> StableOrd for &T {
94 const CAN_USE_UNSTABLE_SORT: bool = T::CAN_USE_UNSTABLE_SORT;
95
96 // Ordering of a reference is exactly that of the referent, and since
97 // the ordering of the referet is stable so must be the ordering of the
98 // reference.
99 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
100}
101
102/// This is a companion trait to `StableOrd`. Some types like `Symbol` can be
103/// compared in a cross-session stable way, but their `Ord` implementation is
104/// not stable. In such cases, a `StableOrd` implementation can be provided
105/// to offer a lightweight way for stable sorting. (The more heavyweight option
106/// is to sort via `ToStableHashKey`, but then sorting needs to have access to
107/// a stable hashing context and `ToStableHashKey` can also be expensive as in
108/// the case of `Symbol` where it has to allocate a `String`.)
109///
110/// See the documentation of [StableOrd] for how stable sort order is defined.
111/// The same definition applies here. Be careful when implementing this trait.
112pub trait StableCompare {
113 const CAN_USE_UNSTABLE_SORT: bool;
114
115 fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering;
116}
117
118/// `StableOrd` denotes that the type's `Ord` implementation is stable, so
119/// we can implement `StableCompare` by just delegating to `Ord`.
120impl<T: StableOrd> StableCompare for T {
121 const CAN_USE_UNSTABLE_SORT: bool = T::CAN_USE_UNSTABLE_SORT;
122
123 fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering {
124 self.cmp(other)
125 }
126}
127
128/// Implement HashStable by just calling `Hash::hash()`. Also implement `StableOrd` for the type since
129/// that has the same requirements.
130///
131/// **WARNING** This is only valid for types that *really* don't need any context for fingerprinting.
132/// But it is easy to misuse this macro (see [#96013](https://github.com/rust-lang/rust/issues/96013)
133/// for examples). Therefore this macro is not exported and should only be used in the limited cases
134/// here in this module.
135///
136/// Use `#[derive(HashStable_Generic)]` instead.
137macro_rules! impl_stable_traits_for_trivial_type {
138 ($t:ty) => {
139 impl<CTX> <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>c</mi><mi>r</mi><mi>a</mi><mi>t</mi><mi>e</mi><mo>:</mo><mo>:</mo><mi>s</mi><mi>t</mi><mi>a</mi><mi>b</mi><mi>l</mi><msub><mi>e</mi><mi>h</mi></msub><mi>a</mi><mi>s</mi><mi>h</mi><mi>e</mi><mi>r</mi><mo>:</mo><mo>:</mo><mi>H</mi><mi>a</mi><mi>s</mi><mi>h</mi><mi>S</mi><mi>t</mi><mi>a</mi><mi>b</mi><mi>l</mi><mi>e</mi><mo><</mo><mi>C</mi><mi>T</mi><mi>X</mi><mo>></mo><mi>f</mi><mi>o</mi><mi>r</mi></mrow><annotation encoding="application/x-tex">crate::stable_hasher::HashStable<CTX> for </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6151em;"></span><span class="mord mathnormal" style="margin-right:0.02778em;">cr</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">::</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8444em;vertical-align:-0.15em;"></span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mord mathnormal">ab</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord"><span class="mord mathnormal">e</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">h</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">a</span><span class="mord mathnormal">s</span><span class="mord mathnormal">h</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">::</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.7335em;vertical-align:-0.0391em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal">a</span><span class="mord mathnormal">s</span><span class="mord mathnormal">h</span><span class="mord mathnormal">St</span><span class="mord mathnormal">ab</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel"><</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.7224em;vertical-align:-0.0391em;"></span><span class="mord mathnormal" style="margin-right:0.07847em;">CTX</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">></span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span></span></span></span>t {
140 #[inline]
141 fn hash_stable(&self, _: &mut CTX, hasher: &mut $crate::stable_hasher::StableHasher) {
142 ::std::hash::Hash::hash(self, hasher);
143 }
144 }
145
146 impl <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>c</mi><mi>r</mi><mi>a</mi><mi>t</mi><mi>e</mi><mo>:</mo><mo>:</mo><mi>s</mi><mi>t</mi><mi>a</mi><mi>b</mi><mi>l</mi><msub><mi>e</mi><mi>h</mi></msub><mi>a</mi><mi>s</mi><mi>h</mi><mi>e</mi><mi>r</mi><mo>:</mo><mo>:</mo><mi>S</mi><mi>t</mi><mi>a</mi><mi>b</mi><mi>l</mi><mi>e</mi><mi>O</mi><mi>r</mi><mi>d</mi><mi>f</mi><mi>o</mi><mi>r</mi></mrow><annotation encoding="application/x-tex">crate::stable_hasher::StableOrd for </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6151em;"></span><span class="mord mathnormal" style="margin-right:0.02778em;">cr</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">::</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8444em;vertical-align:-0.15em;"></span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mord mathnormal">ab</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord"><span class="mord mathnormal">e</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">h</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">a</span><span class="mord mathnormal">s</span><span class="mord mathnormal">h</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">::</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">St</span><span class="mord mathnormal">ab</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.02778em;">O</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal" style="margin-right:0.10764em;">df</span><span class="mord mathnormal" style="margin-right:0.02778em;">or</span></span></span></span>t {
147 const CAN_USE_UNSTABLE_SORT: bool = true;
148
149 // Encoding and decoding doesn't change the bytes of trivial types
150 // and `Ord::cmp` depends only on those bytes.
151 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
152 }
153 };
154}
155
156pub(crate) use impl_stable_traits_for_trivial_type;
157
158impl_stable_traits_for_trivial_type!(i8);
159impl_stable_traits_for_trivial_type!(i16);
160impl_stable_traits_for_trivial_type!(i32);
161impl_stable_traits_for_trivial_type!(i64);
162impl_stable_traits_for_trivial_type!(isize);
163
164impl_stable_traits_for_trivial_type!(u8);
165impl_stable_traits_for_trivial_type!(u16);
166impl_stable_traits_for_trivial_type!(u32);
167impl_stable_traits_for_trivial_type!(u64);
168impl_stable_traits_for_trivial_type!(usize);
169
170impl_stable_traits_for_trivial_type!(u128);
171impl_stable_traits_for_trivial_type!(i128);
172
173impl_stable_traits_for_trivial_type!(char);
174impl_stable_traits_for_trivial_type!(());
175
176impl_stable_traits_for_trivial_type!(Hash64);
177
178// We need a custom impl as the default hash function will only hash half the bits. For stable
179// hashing we want to hash the full 128-bit hash.
180impl<CTX> HashStable<CTX> for Hash128 {
181 #[inline]
182 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
183 self.as_u128().hash(hasher);
184 }
185}
186
187impl StableOrd for Hash128 {
188 const CAN_USE_UNSTABLE_SORT: bool = true;
189
190 // Encoding and decoding doesn't change the bytes of `Hash128`
191 // and `Ord::cmp` depends only on those bytes.
192 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
193}
194
195impl<CTX> HashStable<CTX> for ! {
196 fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {
197 unreachable!()
198 }
199}
200
201impl<CTX, T> HashStable<CTX> for PhantomData<T> {
202 fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {}
203}
204
205impl<CTX> HashStable<CTX> for NonZero<u32> {
206 #[inline]
207 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
208 self.get().hash_stable(ctx, hasher)
209 }
210}
211
212impl<CTX> HashStable<CTX> for NonZero<usize> {
213 #[inline]
214 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
215 self.get().hash_stable(ctx, hasher)
216 }
217}
218
219impl<CTX> HashStable<CTX> for f32 {
220 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
221 let val: u32 = self.to_bits();
222 val.hash_stable(ctx, hasher);
223 }
224}
225
226impl<CTX> HashStable<CTX> for f64 {
227 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
228 let val: u64 = self.to_bits();
229 val.hash_stable(ctx, hasher);
230 }
231}
232
233impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
234 #[inline]
235 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
236 (*self as i8).hash_stable(ctx, hasher);
237 }
238}
239
240impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
241 #[inline]
242 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
243 let (ref _0,) = *self;
244 _0.hash_stable(ctx, hasher);
245 }
246}
247
248impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
249 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
250 let (ref _0, ref _1) = *self;
251 _0.hash_stable(ctx, hasher);
252 _1.hash_stable(ctx, hasher);
253 }
254}
255
256impl<T1: StableOrd, T2: StableOrd> StableOrd for (T1, T2) {
257 const CAN_USE_UNSTABLE_SORT: bool = T1::CAN_USE_UNSTABLE_SORT && T2::CAN_USE_UNSTABLE_SORT;
258
259 // Ordering of tuples is a pure function of their elements' ordering, and since
260 // the ordering of each element is stable so must be the ordering of the tuple.
261 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
262}
263
264impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
265where
266 T1: HashStable<CTX>,
267 T2: HashStable<CTX>,
268 T3: HashStable<CTX>,
269{
270 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
271 let (ref _0, ref _1, ref _2) = *self;
272 _0.hash_stable(ctx, hasher);
273 _1.hash_stable(ctx, hasher);
274 _2.hash_stable(ctx, hasher);
275 }
276}
277
278impl<T1: StableOrd, T2: StableOrd, T3: StableOrd> StableOrd for (T1, T2, T3) {
279 const CAN_USE_UNSTABLE_SORT: bool =
280 T1::CAN_USE_UNSTABLE_SORT && T2::CAN_USE_UNSTABLE_SORT && T3::CAN_USE_UNSTABLE_SORT;
281
282 // Ordering of tuples is a pure function of their elements' ordering, and since
283 // the ordering of each element is stable so must be the ordering of the tuple.
284 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
285}
286
287impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
288where
289 T1: HashStable<CTX>,
290 T2: HashStable<CTX>,
291 T3: HashStable<CTX>,
292 T4: HashStable<CTX>,
293{
294 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
295 let (ref _0, ref _1, ref _2, ref _3) = *self;
296 _0.hash_stable(ctx, hasher);
297 _1.hash_stable(ctx, hasher);
298 _2.hash_stable(ctx, hasher);
299 _3.hash_stable(ctx, hasher);
300 }
301}
302
303impl<T1: StableOrd, T2: StableOrd, T3: StableOrd, T4: StableOrd> StableOrd for (T1, T2, T3, T4) {
304 const CAN_USE_UNSTABLE_SORT: bool = T1::CAN_USE_UNSTABLE_SORT
305 && T2::CAN_USE_UNSTABLE_SORT
306 && T3::CAN_USE_UNSTABLE_SORT
307 && T4::CAN_USE_UNSTABLE_SORT;
308
309 // Ordering of tuples is a pure function of their elements' ordering, and since
310 // the ordering of each element is stable so must be the ordering of the tuple.
311 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
312}
313
314impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
315 default fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
316 self.len().hash_stable(ctx, hasher);
317 for item in self {
318 item.hash_stable(ctx, hasher);
319 }
320 }
321}
322
323impl<CTX> HashStable<CTX> for [u8] {
324 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
325 self.len().hash_stable(ctx, hasher);
326 hasher.write(self);
327 }
328}
329
330impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
331 #[inline]
332 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
333 self[..].hash_stable(ctx, hasher);
334 }
335}
336
337impl<K, V, R, CTX> HashStable<CTX> for indexmap::IndexMap<K, V, R>
338where
339 K: HashStable<CTX> + Eq + Hash,
340 V: HashStable<CTX>,
341 R: BuildHasher,
342{
343 #[inline]
344 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
345 self.len().hash_stable(ctx, hasher);
346 for kv in self {
347 kv.hash_stable(ctx, hasher);
348 }
349 }
350}
351
352impl<K, R, CTX> HashStable<CTX> for indexmap::IndexSet<K, R>
353where
354 K: HashStable<CTX> + Eq + Hash,
355 R: BuildHasher,
356{
357 #[inline]
358 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
359 self.len().hash_stable(ctx, hasher);
360 for key in self {
361 key.hash_stable(ctx, hasher);
362 }
363 }
364}
365
366impl<A, const N: usize, CTX> HashStable<CTX> for SmallVec<[A; N]>
367where
368 A: HashStable<CTX>,
369{
370 #[inline]
371 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
372 self[..].hash_stable(ctx, hasher);
373 }
374}
375
376impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
377 #[inline]
378 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
379 (**self).hash_stable(ctx, hasher);
380 }
381}
382
383impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
384 #[inline]
385 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
386 (**self).hash_stable(ctx, hasher);
387 }
388}
389
390impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
391 #[inline]
392 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
393 (**self).hash_stable(ctx, hasher);
394 }
395}
396
397impl<CTX> HashStable<CTX> for str {
398 #[inline]
399 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
400 self.as_bytes().hash_stable(ctx, hasher);
401 }
402}
403
404impl StableOrd for &str {
405 const CAN_USE_UNSTABLE_SORT: bool = true;
406
407 // Encoding and decoding doesn't change the bytes of string slices
408 // and `Ord::cmp` depends only on those bytes.
409 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
410}
411
412impl<CTX> HashStable<CTX> for String {
413 #[inline]
414 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
415 self[..].hash_stable(hcx, hasher);
416 }
417}
418
419impl StableOrd for String {
420 const CAN_USE_UNSTABLE_SORT: bool = true;
421
422 // String comparison only depends on their contents and the
423 // contents are not changed by (de-)serialization.
424 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
425}
426
427impl<HCX> ToStableHashKey<HCX> for String {
428 type KeyType = String;
429 #[inline]
430 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
431 self.clone()
432 }
433}
434
435impl<HCX, T1: ToStableHashKey<HCX>, T2: ToStableHashKey<HCX>> ToStableHashKey<HCX> for (T1, T2) {
436 type KeyType = (T1::KeyType, T2::KeyType);
437 #[inline]
438 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType {
439 (self.0.to_stable_hash_key(hcx), self.1.to_stable_hash_key(hcx))
440 }
441}
442
443impl<CTX> HashStable<CTX> for bool {
444 #[inline]
445 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
446 (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
447 }
448}
449
450impl StableOrd for bool {
451 const CAN_USE_UNSTABLE_SORT: bool = true;
452
453 // sort order of bools is not changed by (de-)serialization.
454 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
455}
456
457impl<T, CTX> HashStable<CTX> for Option<T>
458where
459 T: HashStable<CTX>,
460{
461 #[inline]
462 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
463 if let Some(ref value) = *self {
464 1u8.hash_stable(ctx, hasher);
465 value.hash_stable(ctx, hasher);
466 } else {
467 0u8.hash_stable(ctx, hasher);
468 }
469 }
470}
471
472impl<T: StableOrd> StableOrd for Option<T> {
473 const CAN_USE_UNSTABLE_SORT: bool = T::CAN_USE_UNSTABLE_SORT;
474
475 // the Option wrapper does not add instability to comparison.
476 const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
477}
478
479impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
480where
481 T1: HashStable<CTX>,
482 T2: HashStable<CTX>,
483{
484 #[inline]
485 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
486 mem::discriminant(self).hash_stable(ctx, hasher);
487 match *self {
488 Ok(ref x) => x.hash_stable(ctx, hasher),
489 Err(ref x) => x.hash_stable(ctx, hasher),
490 }
491 }
492}
493
494impl<'a, T, CTX> HashStable<CTX> for &'a T
495where
496 T: HashStable<CTX> + ?Sized,
497{
498 #[inline]
499 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
500 (**self).hash_stable(ctx, hasher);
501 }
502}
503
504impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
505 #[inline]
506 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
507 ::std::hash::Hash::hash(self, hasher);
508 }
509}
510
511impl<T, CTX> HashStable<CTX> for ::std::ops::RangeInclusive<T>
512where
513 T: HashStable<CTX>,
514{
515 #[inline]
516 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
517 self.start().hash_stable(ctx, hasher);
518 self.end().hash_stable(ctx, hasher);
519 }
520}
521
522impl<I: Idx, T, CTX> HashStable<CTX> for IndexSlice<I, T>
523where
524 T: HashStable<CTX>,
525{
526 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
527 self.len().hash_stable(ctx, hasher);
528 for v in &self.raw {
529 v.hash_stable(ctx, hasher);
530 }
531 }
532}
533
534impl<I: Idx, T, CTX> HashStable<CTX> for IndexVec<I, T>
535where
536 T: HashStable<CTX>,
537{
538 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
539 self.len().hash_stable(ctx, hasher);
540 for v in &self.raw {
541 v.hash_stable(ctx, hasher);
542 }
543 }
544}
545
546impl<I: Idx, CTX> HashStable<CTX> for DenseBitSet<I> {
547 fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
548 ::std::hash::Hash::hash(self, hasher);
549 }
550}
551
552impl<R: Idx, C: Idx, CTX> HashStable<CTX> for bit_set::BitMatrix<R, C> {
553 fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
554 ::std::hash::Hash::hash(self, hasher);
555 }
556}
557
558impl<T, CTX> HashStable<CTX> for bit_set::FiniteBitSet<T>
559where
560 T: HashStable<CTX> + bit_set::FiniteBitSetTy,
561{
562 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
563 self.0.hash_stable(hcx, hasher);
564 }
565}
566
567impl_stable_traits_for_trivial_type!(::std::ffi::OsStr);
568
569impl_stable_traits_for_trivial_type!(::std::path::Path);
570impl_stable_traits_for_trivial_type!(::std::path::PathBuf);
571
572// It is not safe to implement HashStable for HashSet, HashMap or any other collection type
573// with unstable but observable iteration order.
574// See https://github.com/rust-lang/compiler-team/issues/533 for further information.
575impl<V, HCX> !HashStable<HCX> for std::collections::HashSet<V> {}
576impl<K, V, HCX> !HashStable<HCX> for std::collections::HashMap<K, V> {}
577
578impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
579where
580 K: HashStable<HCX> + StableOrd,
581 V: HashStable<HCX>,
582{
583 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
584 self.len().hash_stable(hcx, hasher);
585 for entry in self.iter() {
586 entry.hash_stable(hcx, hasher);
587 }
588 }
589}
590
591impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
592where
593 K: HashStable<HCX> + StableOrd,
594{
595 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
596 self.len().hash_stable(hcx, hasher);
597 for entry in self.iter() {
598 entry.hash_stable(hcx, hasher);
599 }
600 }
601}
602
603/// Controls what data we do or do not hash.
604/// Whenever a `HashStable` implementation caches its
605/// result, it needs to include `HashingControls` as part
606/// of the key, to ensure that it does not produce an incorrect
607/// result (for example, using a `Fingerprint` produced while
608/// hashing `Span`s when a `Fingerprint` without `Span`s is
609/// being requested)
610#[derive(Clone, Hash, Eq, PartialEq, Debug)]
611pub struct HashingControls {
612 pub hash_spans: bool,
613}