1 use std::hash::{Hash, Hasher, BuildHasher};
3 use smallvec::SmallVec;
4 use crate::sip128::SipHasher128;
6 use rustc_index::bit_set;
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 {
32 state: SipHasher128::new_with_keys(0, 0),
36 pub fn finish<W: StableHasherResult>(self) -> W {
41 impl StableHasherResult for u128 {
42 fn finish(hasher: StableHasher) -> Self {
43 let (_0, _1) = hasher.finalize();
44 u128::from(_0) | (u128::from(_1) << 64)
48 impl StableHasherResult for u64 {
49 fn finish(hasher: StableHasher) -> Self {
56 pub fn finalize(self) -> (u64, u64) {
57 self.state.finish128()
61 impl Hasher for StableHasher {
62 fn finish(&self) -> u64 {
63 panic!("use StableHasher::finalize instead");
67 fn write(&mut self, bytes: &[u8]) {
68 self.state.write(bytes);
72 fn write_u8(&mut self, i: u8) {
73 self.state.write_u8(i);
77 fn write_u16(&mut self, i: u16) {
78 self.state.write_u16(i.to_le());
82 fn write_u32(&mut self, i: u32) {
83 self.state.write_u32(i.to_le());
87 fn write_u64(&mut self, i: u64) {
88 self.state.write_u64(i.to_le());
92 fn write_u128(&mut self, i: u128) {
93 self.state.write_u128(i.to_le());
97 fn write_usize(&mut self, i: usize) {
98 // Always treat usize as u64 so we get the same results on 32 and 64 bit
99 // platforms. This is important for symbol hashes when cross compiling,
101 self.state.write_u64((i as u64).to_le());
105 fn write_i8(&mut self, i: i8) {
106 self.state.write_i8(i);
110 fn write_i16(&mut self, i: i16) {
111 self.state.write_i16(i.to_le());
115 fn write_i32(&mut self, i: i32) {
116 self.state.write_i32(i.to_le());
120 fn write_i64(&mut self, i: i64) {
121 self.state.write_i64(i.to_le());
125 fn write_i128(&mut self, i: i128) {
126 self.state.write_i128(i.to_le());
130 fn write_isize(&mut self, i: isize) {
131 // Always treat isize as i64 so we get the same results on 32 and 64 bit
132 // platforms. This is important for symbol hashes when cross compiling,
134 self.state.write_i64((i as i64).to_le());
138 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
139 /// stable across multiple compilation sessions.
141 /// Note that `HashStable` imposes rather more strict requirements than usual
144 /// - Stable hashes are sometimes used as identifiers. Therefore they must
145 /// conform to the corresponding `PartialEq` implementations:
147 /// - `x == y` implies `hash_stable(x) == hash_stable(y)`, and
148 /// - `x != y` implies `hash_stable(x) != hash_stable(y)`.
150 /// That second condition is usually not required for hash functions
151 /// (e.g. `Hash`). In practice this means that `hash_stable` must feed any
152 /// information into the hasher that a `PartialEq` comparision takes into
153 /// account. See [#49300](https://github.com/rust-lang/rust/issues/49300)
154 /// for an example where violating this invariant has caused trouble in the
157 /// - `hash_stable()` must be independent of the current
158 /// compilation session. E.g. they must not hash memory addresses or other
159 /// things that are "randomly" assigned per compilation session.
161 /// - `hash_stable()` must be independent of the host architecture. The
162 /// `StableHasher` takes care of endianness and `isize`/`usize` platform
164 pub trait HashStable<CTX> {
165 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher);
168 /// Implement this for types that can be turned into stable keys like, for
169 /// example, for DefId that can be converted to a DefPathHash. This is used for
170 /// bringing maps into a predictable order before hashing them.
171 pub trait ToStableHashKey<HCX> {
172 type KeyType: Ord + Sized + HashStable<HCX>;
173 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
176 // Implement HashStable by just calling `Hash::hash()`. This works fine for
177 // self-contained values that don't depend on the hashing context `CTX`.
179 macro_rules! impl_stable_hash_via_hash {
181 impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
186 hasher: &mut $crate::stable_hasher::StableHasher
188 ::std::hash::Hash::hash(self, hasher);
194 impl_stable_hash_via_hash!(i8);
195 impl_stable_hash_via_hash!(i16);
196 impl_stable_hash_via_hash!(i32);
197 impl_stable_hash_via_hash!(i64);
198 impl_stable_hash_via_hash!(isize);
200 impl_stable_hash_via_hash!(u8);
201 impl_stable_hash_via_hash!(u16);
202 impl_stable_hash_via_hash!(u32);
203 impl_stable_hash_via_hash!(u64);
204 impl_stable_hash_via_hash!(usize);
206 impl_stable_hash_via_hash!(u128);
207 impl_stable_hash_via_hash!(i128);
209 impl_stable_hash_via_hash!(char);
210 impl_stable_hash_via_hash!(());
212 impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
213 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
214 self.get().hash_stable(ctx, hasher)
218 impl<CTX> HashStable<CTX> for f32 {
219 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
220 let val: u32 = unsafe {
221 ::std::mem::transmute(*self)
223 val.hash_stable(ctx, hasher);
227 impl<CTX> HashStable<CTX> for f64 {
228 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
229 let val: u64 = unsafe {
230 ::std::mem::transmute(*self)
232 val.hash_stable(ctx, hasher);
236 impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
237 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
238 (*self as i8).hash_stable(ctx, hasher);
242 impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
243 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
244 let (ref _0,) = *self;
245 _0.hash_stable(ctx, hasher);
249 impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
250 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
251 let (ref _0, ref _1) = *self;
252 _0.hash_stable(ctx, hasher);
253 _1.hash_stable(ctx, hasher);
257 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
258 where T1: HashStable<CTX>,
262 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
263 let (ref _0, ref _1, ref _2) = *self;
264 _0.hash_stable(ctx, hasher);
265 _1.hash_stable(ctx, hasher);
266 _2.hash_stable(ctx, hasher);
270 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
271 where T1: HashStable<CTX>,
276 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
277 let (ref _0, ref _1, ref _2, ref _3) = *self;
278 _0.hash_stable(ctx, hasher);
279 _1.hash_stable(ctx, hasher);
280 _2.hash_stable(ctx, hasher);
281 _3.hash_stable(ctx, hasher);
285 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
286 default fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
287 self.len().hash_stable(ctx, hasher);
289 item.hash_stable(ctx, hasher);
294 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
296 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
297 (&self[..]).hash_stable(ctx, hasher);
301 impl<K, V, R, CTX> HashStable<CTX> for indexmap::IndexMap<K, V, R>
302 where K: HashStable<CTX> + Eq + Hash,
307 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
308 self.len().hash_stable(ctx, hasher);
310 kv.hash_stable(ctx, hasher);
315 impl<K, R, CTX> HashStable<CTX> for indexmap::IndexSet<K, R>
316 where K: HashStable<CTX> + Eq + Hash,
320 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
321 self.len().hash_stable(ctx, hasher);
323 key.hash_stable(ctx, hasher);
328 impl<A, CTX> HashStable<CTX> for SmallVec<[A; 1]> where A: HashStable<CTX> {
330 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
331 (&self[..]).hash_stable(ctx, hasher);
335 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
337 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
338 (**self).hash_stable(ctx, hasher);
342 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
344 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
345 (**self).hash_stable(ctx, hasher);
349 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
351 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
352 (**self).hash_stable(ctx, hasher);
356 impl<CTX> HashStable<CTX> for str {
358 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
359 self.len().hash(hasher);
360 self.as_bytes().hash(hasher);
365 impl<CTX> HashStable<CTX> for String {
367 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
368 (&self[..]).hash_stable(hcx, hasher);
372 impl<HCX> ToStableHashKey<HCX> for String {
373 type KeyType = String;
375 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
380 impl<CTX> HashStable<CTX> for bool {
382 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
383 (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
388 impl<T, CTX> HashStable<CTX> for Option<T>
389 where T: HashStable<CTX>
392 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
393 if let Some(ref value) = *self {
394 1u8.hash_stable(ctx, hasher);
395 value.hash_stable(ctx, hasher);
397 0u8.hash_stable(ctx, hasher);
402 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
403 where T1: HashStable<CTX>,
407 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
408 mem::discriminant(self).hash_stable(ctx, hasher);
410 Ok(ref x) => x.hash_stable(ctx, hasher),
411 Err(ref x) => x.hash_stable(ctx, hasher),
416 impl<'a, T, CTX> HashStable<CTX> for &'a T
417 where T: HashStable<CTX> + ?Sized
420 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
421 (**self).hash_stable(ctx, hasher);
425 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
427 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
428 ::std::hash::Hash::hash(self, hasher);
432 impl<I: vec::Idx, T, CTX> HashStable<CTX> for vec::IndexVec<I, T>
433 where T: HashStable<CTX>,
435 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
436 self.len().hash_stable(ctx, hasher);
438 v.hash_stable(ctx, hasher);
444 impl<I: vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I>
446 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
447 self.words().hash_stable(ctx, hasher);
451 impl<R: vec::Idx, C: vec::Idx, CTX> HashStable<CTX>
452 for bit_set::BitMatrix<R, C>
454 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
455 self.words().hash_stable(ctx, hasher);
459 impl_stable_hash_via_hash!(::std::path::Path);
460 impl_stable_hash_via_hash!(::std::path::PathBuf);
462 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
463 where K: ToStableHashKey<HCX> + Eq,
468 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
469 hash_stable_hashmap(hcx, hasher, self, ToStableHashKey::to_stable_hash_key);
473 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
474 where K: ToStableHashKey<HCX> + Eq,
477 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
478 let mut keys: Vec<_> = self.iter()
479 .map(|k| k.to_stable_hash_key(hcx))
481 keys.sort_unstable();
482 keys.hash_stable(hcx, hasher);
486 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
487 where K: ToStableHashKey<HCX>,
490 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
491 let mut entries: Vec<_> = self.iter()
492 .map(|(k, v)| (k.to_stable_hash_key(hcx), v))
494 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
495 entries.hash_stable(hcx, hasher);
499 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
500 where K: ToStableHashKey<HCX>,
502 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
503 let mut keys: Vec<_> = self.iter()
504 .map(|k| k.to_stable_hash_key(hcx))
506 keys.sort_unstable();
507 keys.hash_stable(hcx, hasher);
511 pub fn hash_stable_hashmap<HCX, K, V, R, SK, F>(
513 hasher: &mut StableHasher,
514 map: &::std::collections::HashMap<K, V, R>,
515 to_stable_hash_key: F)
519 SK: HashStable<HCX> + Ord,
520 F: Fn(&K, &HCX) -> SK,
522 let mut entries: Vec<_> = map.iter()
523 .map(|(k, v)| (to_stable_hash_key(k, hcx), v))
525 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
526 entries.hash_stable(hcx, hasher);
530 /// A vector container that makes sure that its items are hashed in a stable
532 pub struct StableVec<T>(Vec<T>);
534 impl<T> StableVec<T> {
535 pub fn new(v: Vec<T>) -> Self {
540 impl<T> ::std::ops::Deref for StableVec<T> {
541 type Target = Vec<T>;
543 fn deref(&self) -> &Vec<T> {
548 impl<T, HCX> HashStable<HCX> for StableVec<T>
549 where T: HashStable<HCX> + ToStableHashKey<HCX>
551 fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
552 let StableVec(ref v) = *self;
554 let mut sorted: Vec<_> = v.iter()
555 .map(|x| x.to_stable_hash_key(hcx))
557 sorted.sort_unstable();
558 sorted.hash_stable(hcx, hasher);