1 use crate::sip128::SipHasher128;
2 use rustc_index::bit_set;
4 use smallvec::SmallVec;
5 use std::hash::{BuildHasher, Hash, Hasher};
8 /// When hashing something that ends up affecting properties like symbol names,
9 /// we want these symbol names to be calculated independently of other factors
10 /// like what architecture you're compiling *from*.
12 /// To that end we always convert integers to little-endian format before
13 /// hashing and the architecture dependent `isize` and `usize` types are
14 /// extended to 64 bits if needed.
15 pub struct StableHasher {
19 impl ::std::fmt::Debug for StableHasher {
20 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
21 write!(f, "{:?}", self.state)
25 pub trait StableHasherResult: Sized {
26 fn finish(hasher: StableHasher) -> Self;
30 pub fn new() -> Self {
31 StableHasher { state: SipHasher128::new_with_keys(0, 0) }
34 pub fn finish<W: StableHasherResult>(self) -> W {
39 impl StableHasherResult for u128 {
40 fn finish(hasher: StableHasher) -> Self {
41 let (_0, _1) = hasher.finalize();
42 u128::from(_0) | (u128::from(_1) << 64)
46 impl StableHasherResult for u64 {
47 fn finish(hasher: StableHasher) -> Self {
54 pub fn finalize(self) -> (u64, u64) {
55 self.state.finish128()
59 impl Hasher for StableHasher {
60 fn finish(&self) -> u64 {
61 panic!("use StableHasher::finalize instead");
65 fn write(&mut self, bytes: &[u8]) {
66 self.state.write(bytes);
70 fn write_u8(&mut self, i: u8) {
71 self.state.write_u8(i);
75 fn write_u16(&mut self, i: u16) {
76 self.state.write_u16(i.to_le());
80 fn write_u32(&mut self, i: u32) {
81 self.state.write_u32(i.to_le());
85 fn write_u64(&mut self, i: u64) {
86 self.state.write_u64(i.to_le());
90 fn write_u128(&mut self, i: u128) {
91 self.state.write_u128(i.to_le());
95 fn write_usize(&mut self, i: usize) {
96 // Always treat usize as u64 so we get the same results on 32 and 64 bit
97 // platforms. This is important for symbol hashes when cross compiling,
99 self.state.write_u64((i as u64).to_le());
103 fn write_i8(&mut self, i: i8) {
104 self.state.write_i8(i);
108 fn write_i16(&mut self, i: i16) {
109 self.state.write_i16(i.to_le());
113 fn write_i32(&mut self, i: i32) {
114 self.state.write_i32(i.to_le());
118 fn write_i64(&mut self, i: i64) {
119 self.state.write_i64(i.to_le());
123 fn write_i128(&mut self, i: i128) {
124 self.state.write_i128(i.to_le());
128 fn write_isize(&mut self, i: isize) {
129 // Always treat isize as i64 so we get the same results on 32 and 64 bit
130 // platforms. This is important for symbol hashes when cross compiling,
132 self.state.write_i64((i as i64).to_le());
136 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
137 /// stable across multiple compilation sessions.
139 /// Note that `HashStable` imposes rather more strict requirements than usual
142 /// - Stable hashes are sometimes used as identifiers. Therefore they must
143 /// conform to the corresponding `PartialEq` implementations:
145 /// - `x == y` implies `hash_stable(x) == hash_stable(y)`, and
146 /// - `x != y` implies `hash_stable(x) != hash_stable(y)`.
148 /// That second condition is usually not required for hash functions
149 /// (e.g. `Hash`). In practice this means that `hash_stable` must feed any
150 /// information into the hasher that a `PartialEq` comparison takes into
151 /// account. See [#49300](https://github.com/rust-lang/rust/issues/49300)
152 /// for an example where violating this invariant has caused trouble in the
155 /// - `hash_stable()` must be independent of the current
156 /// compilation session. E.g. they must not hash memory addresses or other
157 /// things that are "randomly" assigned per compilation session.
159 /// - `hash_stable()` must be independent of the host architecture. The
160 /// `StableHasher` takes care of endianness and `isize`/`usize` platform
162 pub trait HashStable<CTX> {
163 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher);
166 /// Implement this for types that can be turned into stable keys like, for
167 /// example, for DefId that can be converted to a DefPathHash. This is used for
168 /// bringing maps into a predictable order before hashing them.
169 pub trait ToStableHashKey<HCX> {
170 type KeyType: Ord + Sized + HashStable<HCX>;
171 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
174 // Implement HashStable by just calling `Hash::hash()`. This works fine for
175 // self-contained values that don't depend on the hashing context `CTX`.
177 macro_rules! impl_stable_hash_via_hash {
179 impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
181 fn hash_stable(&self, _: &mut CTX, hasher: &mut $crate::stable_hasher::StableHasher) {
182 ::std::hash::Hash::hash(self, hasher);
188 impl_stable_hash_via_hash!(i8);
189 impl_stable_hash_via_hash!(i16);
190 impl_stable_hash_via_hash!(i32);
191 impl_stable_hash_via_hash!(i64);
192 impl_stable_hash_via_hash!(isize);
194 impl_stable_hash_via_hash!(u8);
195 impl_stable_hash_via_hash!(u16);
196 impl_stable_hash_via_hash!(u32);
197 impl_stable_hash_via_hash!(u64);
198 impl_stable_hash_via_hash!(usize);
200 impl_stable_hash_via_hash!(u128);
201 impl_stable_hash_via_hash!(i128);
203 impl_stable_hash_via_hash!(char);
204 impl_stable_hash_via_hash!(());
206 impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
207 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
208 self.get().hash_stable(ctx, hasher)
212 impl<CTX> HashStable<CTX> for f32 {
213 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
214 let val: u32 = unsafe { ::std::mem::transmute(*self) };
215 val.hash_stable(ctx, hasher);
219 impl<CTX> HashStable<CTX> for f64 {
220 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
221 let val: u64 = unsafe { ::std::mem::transmute(*self) };
222 val.hash_stable(ctx, hasher);
226 impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
227 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
228 (*self as i8).hash_stable(ctx, hasher);
232 impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
233 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
234 let (ref _0,) = *self;
235 _0.hash_stable(ctx, hasher);
239 impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
240 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
241 let (ref _0, ref _1) = *self;
242 _0.hash_stable(ctx, hasher);
243 _1.hash_stable(ctx, hasher);
247 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
253 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
254 let (ref _0, ref _1, ref _2) = *self;
255 _0.hash_stable(ctx, hasher);
256 _1.hash_stable(ctx, hasher);
257 _2.hash_stable(ctx, hasher);
261 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
268 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
269 let (ref _0, ref _1, ref _2, ref _3) = *self;
270 _0.hash_stable(ctx, hasher);
271 _1.hash_stable(ctx, hasher);
272 _2.hash_stable(ctx, hasher);
273 _3.hash_stable(ctx, hasher);
277 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
278 default fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
279 self.len().hash_stable(ctx, hasher);
281 item.hash_stable(ctx, hasher);
286 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
288 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
289 (&self[..]).hash_stable(ctx, hasher);
293 impl<K, V, R, CTX> HashStable<CTX> for indexmap::IndexMap<K, V, R>
295 K: HashStable<CTX> + Eq + Hash,
300 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
301 self.len().hash_stable(ctx, hasher);
303 kv.hash_stable(ctx, hasher);
308 impl<K, R, CTX> HashStable<CTX> for indexmap::IndexSet<K, R>
310 K: HashStable<CTX> + Eq + Hash,
314 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
315 self.len().hash_stable(ctx, hasher);
317 key.hash_stable(ctx, hasher);
322 impl<A, CTX> HashStable<CTX> for SmallVec<[A; 1]>
327 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
328 (&self[..]).hash_stable(ctx, hasher);
332 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
334 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
335 (**self).hash_stable(ctx, hasher);
339 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
341 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
342 (**self).hash_stable(ctx, hasher);
346 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
348 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
349 (**self).hash_stable(ctx, hasher);
353 impl<CTX> HashStable<CTX> for str {
355 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
356 self.len().hash(hasher);
357 self.as_bytes().hash(hasher);
361 impl<CTX> HashStable<CTX> for String {
363 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
364 (&self[..]).hash_stable(hcx, hasher);
368 impl<HCX> ToStableHashKey<HCX> for String {
369 type KeyType = String;
371 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
376 impl<CTX> HashStable<CTX> for bool {
378 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
379 (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
383 impl<T, CTX> HashStable<CTX> for Option<T>
388 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
389 if let Some(ref value) = *self {
390 1u8.hash_stable(ctx, hasher);
391 value.hash_stable(ctx, hasher);
393 0u8.hash_stable(ctx, hasher);
398 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
404 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
405 mem::discriminant(self).hash_stable(ctx, hasher);
407 Ok(ref x) => x.hash_stable(ctx, hasher),
408 Err(ref x) => x.hash_stable(ctx, hasher),
413 impl<'a, T, CTX> HashStable<CTX> for &'a T
415 T: HashStable<CTX> + ?Sized,
418 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
419 (**self).hash_stable(ctx, hasher);
423 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
425 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
426 ::std::hash::Hash::hash(self, hasher);
430 impl<T, CTX> HashStable<CTX> for ::std::ops::RangeInclusive<T>
435 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
436 self.start().hash_stable(ctx, hasher);
437 self.end().hash_stable(ctx, hasher);
441 impl<I: vec::Idx, T, CTX> HashStable<CTX> for vec::IndexVec<I, T>
445 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
446 self.len().hash_stable(ctx, hasher);
448 v.hash_stable(ctx, hasher);
453 impl<I: vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I> {
454 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
455 self.words().hash_stable(ctx, hasher);
459 impl<R: vec::Idx, C: vec::Idx, CTX> HashStable<CTX> for bit_set::BitMatrix<R, C> {
460 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
461 self.words().hash_stable(ctx, hasher);
465 impl_stable_hash_via_hash!(::std::path::Path);
466 impl_stable_hash_via_hash!(::std::path::PathBuf);
468 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
470 K: ToStableHashKey<HCX> + Eq,
475 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
476 hash_stable_hashmap(hcx, hasher, self, ToStableHashKey::to_stable_hash_key);
480 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
482 K: ToStableHashKey<HCX> + Eq,
485 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
486 let mut keys: Vec<_> = self.iter().map(|k| k.to_stable_hash_key(hcx)).collect();
487 keys.sort_unstable();
488 keys.hash_stable(hcx, hasher);
492 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
494 K: ToStableHashKey<HCX>,
497 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
498 let mut entries: Vec<_> =
499 self.iter().map(|(k, v)| (k.to_stable_hash_key(hcx), v)).collect();
500 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
501 entries.hash_stable(hcx, hasher);
505 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
507 K: ToStableHashKey<HCX>,
509 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
510 let mut keys: Vec<_> = self.iter().map(|k| k.to_stable_hash_key(hcx)).collect();
511 keys.sort_unstable();
512 keys.hash_stable(hcx, hasher);
516 pub fn hash_stable_hashmap<HCX, K, V, R, SK, F>(
518 hasher: &mut StableHasher,
519 map: &::std::collections::HashMap<K, V, R>,
520 to_stable_hash_key: F,
525 SK: HashStable<HCX> + Ord,
526 F: Fn(&K, &HCX) -> SK,
528 let mut entries: Vec<_> = map.iter().map(|(k, v)| (to_stable_hash_key(k, hcx), v)).collect();
529 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
530 entries.hash_stable(hcx, hasher);
533 /// A vector container that makes sure that its items are hashed in a stable
535 pub struct StableVec<T>(Vec<T>);
537 impl<T> StableVec<T> {
538 pub fn new(v: Vec<T>) -> Self {
543 impl<T> ::std::ops::Deref for StableVec<T> {
544 type Target = Vec<T>;
546 fn deref(&self) -> &Vec<T> {
551 impl<T, HCX> HashStable<HCX> for StableVec<T>
553 T: HashStable<HCX> + ToStableHashKey<HCX>,
555 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
556 let StableVec(ref v) = *self;
558 let mut sorted: Vec<_> = v.iter().map(|x| x.to_stable_hash_key(hcx)).collect();
559 sorted.sort_unstable();
560 sorted.hash_stable(hcx, hasher);