1 use std::hash::{Hash, Hasher, BuildHasher};
2 use std::marker::PhantomData;
4 use smallvec::SmallVec;
5 use crate::sip128::SipHasher128;
6 use crate::indexed_vec;
9 /// When hashing something that ends up affecting properties like symbol names,
10 /// we want these symbol names to be calculated independently of other factors
11 /// like what architecture you're compiling *from*.
13 /// To that end we always convert integers to little-endian format before
14 /// hashing and the architecture dependent `isize` and `usize` types are
15 /// extended to 64 bits if needed.
16 pub struct StableHasher<W> {
18 width: PhantomData<W>,
21 impl<W: StableHasherResult> ::std::fmt::Debug for StableHasher<W> {
22 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
23 write!(f, "{:?}", self.state)
27 pub trait StableHasherResult: Sized {
28 fn finish(hasher: StableHasher<Self>) -> Self;
31 impl<W: StableHasherResult> StableHasher<W> {
32 pub fn new() -> Self {
34 state: SipHasher128::new_with_keys(0, 0),
39 pub fn finish(self) -> W {
44 impl StableHasherResult for u128 {
45 fn finish(hasher: StableHasher<Self>) -> Self {
46 let (_0, _1) = hasher.finalize();
47 (_0 as u128) | ((_1 as u128) << 64)
51 impl StableHasherResult for u64 {
52 fn finish(hasher: StableHasher<Self>) -> Self {
57 impl<W> StableHasher<W> {
59 pub fn finalize(self) -> (u64, u64) {
60 self.state.finish128()
64 impl<W> Hasher for StableHasher<W> {
65 fn finish(&self) -> u64 {
66 panic!("use StableHasher::finalize instead");
70 fn write(&mut self, bytes: &[u8]) {
71 self.state.write(bytes);
75 fn write_u8(&mut self, i: u8) {
76 self.state.write_u8(i);
80 fn write_u16(&mut self, i: u16) {
81 self.state.write_u16(i.to_le());
85 fn write_u32(&mut self, i: u32) {
86 self.state.write_u32(i.to_le());
90 fn write_u64(&mut self, i: u64) {
91 self.state.write_u64(i.to_le());
95 fn write_u128(&mut self, i: u128) {
96 self.state.write_u128(i.to_le());
100 fn write_usize(&mut self, i: usize) {
101 // Always treat usize as u64 so we get the same results on 32 and 64 bit
102 // platforms. This is important for symbol hashes when cross compiling,
104 self.state.write_u64((i as u64).to_le());
108 fn write_i8(&mut self, i: i8) {
109 self.state.write_i8(i);
113 fn write_i16(&mut self, i: i16) {
114 self.state.write_i16(i.to_le());
118 fn write_i32(&mut self, i: i32) {
119 self.state.write_i32(i.to_le());
123 fn write_i64(&mut self, i: i64) {
124 self.state.write_i64(i.to_le());
128 fn write_i128(&mut self, i: i128) {
129 self.state.write_i128(i.to_le());
133 fn write_isize(&mut self, i: isize) {
134 // Always treat isize as i64 so we get the same results on 32 and 64 bit
135 // platforms. This is important for symbol hashes when cross compiling,
137 self.state.write_i64((i as i64).to_le());
141 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
142 /// stable across multiple compilation sessions.
143 pub trait HashStable<CTX> {
144 fn hash_stable<W: StableHasherResult>(&self,
146 hasher: &mut StableHasher<W>);
149 /// Implement this for types that can be turned into stable keys like, for
150 /// example, for DefId that can be converted to a DefPathHash. This is used for
151 /// bringing maps into a predictable order before hashing them.
152 pub trait ToStableHashKey<HCX> {
153 type KeyType: Ord + Clone + Sized + HashStable<HCX>;
154 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
157 // Implement HashStable by just calling `Hash::hash()`. This works fine for
158 // self-contained values that don't depend on the hashing context `CTX`.
160 macro_rules! impl_stable_hash_via_hash {
162 impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
164 fn hash_stable<W: $crate::stable_hasher::StableHasherResult>(
167 hasher: &mut $crate::stable_hasher::StableHasher<W>
169 ::std::hash::Hash::hash(self, hasher);
175 impl_stable_hash_via_hash!(i8);
176 impl_stable_hash_via_hash!(i16);
177 impl_stable_hash_via_hash!(i32);
178 impl_stable_hash_via_hash!(i64);
179 impl_stable_hash_via_hash!(isize);
181 impl_stable_hash_via_hash!(u8);
182 impl_stable_hash_via_hash!(u16);
183 impl_stable_hash_via_hash!(u32);
184 impl_stable_hash_via_hash!(u64);
185 impl_stable_hash_via_hash!(usize);
187 impl_stable_hash_via_hash!(u128);
188 impl_stable_hash_via_hash!(i128);
190 impl_stable_hash_via_hash!(char);
191 impl_stable_hash_via_hash!(());
193 impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
194 fn hash_stable<W: StableHasherResult>(&self,
196 hasher: &mut StableHasher<W>) {
197 self.get().hash_stable(ctx, hasher)
201 impl<CTX> HashStable<CTX> for f32 {
202 fn hash_stable<W: StableHasherResult>(&self,
204 hasher: &mut StableHasher<W>) {
205 let val: u32 = unsafe {
206 ::std::mem::transmute(*self)
208 val.hash_stable(ctx, hasher);
212 impl<CTX> HashStable<CTX> for f64 {
213 fn hash_stable<W: StableHasherResult>(&self,
215 hasher: &mut StableHasher<W>) {
216 let val: u64 = unsafe {
217 ::std::mem::transmute(*self)
219 val.hash_stable(ctx, hasher);
223 impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
224 fn hash_stable<W: StableHasherResult>(&self,
226 hasher: &mut StableHasher<W>) {
227 (*self as i8).hash_stable(ctx, hasher);
231 impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
232 fn hash_stable<W: StableHasherResult>(&self,
234 hasher: &mut StableHasher<W>) {
235 let (ref _0,) = *self;
236 _0.hash_stable(ctx, hasher);
240 impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
241 fn hash_stable<W: StableHasherResult>(&self,
243 hasher: &mut StableHasher<W>) {
244 let (ref _0, ref _1) = *self;
245 _0.hash_stable(ctx, hasher);
246 _1.hash_stable(ctx, hasher);
250 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
251 where T1: HashStable<CTX>,
255 fn hash_stable<W: StableHasherResult>(&self,
257 hasher: &mut StableHasher<W>) {
258 let (ref _0, ref _1, ref _2) = *self;
259 _0.hash_stable(ctx, hasher);
260 _1.hash_stable(ctx, hasher);
261 _2.hash_stable(ctx, hasher);
265 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
266 where T1: HashStable<CTX>,
271 fn hash_stable<W: StableHasherResult>(&self,
273 hasher: &mut StableHasher<W>) {
274 let (ref _0, ref _1, ref _2, ref _3) = *self;
275 _0.hash_stable(ctx, hasher);
276 _1.hash_stable(ctx, hasher);
277 _2.hash_stable(ctx, hasher);
278 _3.hash_stable(ctx, hasher);
282 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
283 default fn hash_stable<W: StableHasherResult>(&self,
285 hasher: &mut StableHasher<W>) {
286 self.len().hash_stable(ctx, hasher);
288 item.hash_stable(ctx, hasher);
293 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
295 fn hash_stable<W: StableHasherResult>(&self,
297 hasher: &mut StableHasher<W>) {
298 (&self[..]).hash_stable(ctx, hasher);
302 impl<A, CTX> HashStable<CTX> for SmallVec<[A; 1]> where A: HashStable<CTX> {
304 fn hash_stable<W: StableHasherResult>(&self,
306 hasher: &mut StableHasher<W>) {
307 (&self[..]).hash_stable(ctx, hasher);
311 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
313 fn hash_stable<W: StableHasherResult>(&self,
315 hasher: &mut StableHasher<W>) {
316 (**self).hash_stable(ctx, hasher);
320 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
322 fn hash_stable<W: StableHasherResult>(&self,
324 hasher: &mut StableHasher<W>) {
325 (**self).hash_stable(ctx, hasher);
329 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
331 fn hash_stable<W: StableHasherResult>(&self,
333 hasher: &mut StableHasher<W>) {
334 (**self).hash_stable(ctx, hasher);
338 impl<CTX> HashStable<CTX> for str {
340 fn hash_stable<W: StableHasherResult>(&self,
342 hasher: &mut StableHasher<W>) {
343 self.len().hash(hasher);
344 self.as_bytes().hash(hasher);
349 impl<CTX> HashStable<CTX> for String {
351 fn hash_stable<W: StableHasherResult>(&self,
353 hasher: &mut StableHasher<W>) {
354 (&self[..]).hash_stable(hcx, hasher);
358 impl<HCX> ToStableHashKey<HCX> for String {
359 type KeyType = String;
361 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
366 impl<CTX> HashStable<CTX> for bool {
368 fn hash_stable<W: StableHasherResult>(&self,
370 hasher: &mut StableHasher<W>) {
371 (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
376 impl<T, CTX> HashStable<CTX> for Option<T>
377 where T: HashStable<CTX>
380 fn hash_stable<W: StableHasherResult>(&self,
382 hasher: &mut StableHasher<W>) {
383 if let Some(ref value) = *self {
384 1u8.hash_stable(ctx, hasher);
385 value.hash_stable(ctx, hasher);
387 0u8.hash_stable(ctx, hasher);
392 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
393 where T1: HashStable<CTX>,
397 fn hash_stable<W: StableHasherResult>(&self,
399 hasher: &mut StableHasher<W>) {
400 mem::discriminant(self).hash_stable(ctx, hasher);
402 Ok(ref x) => x.hash_stable(ctx, hasher),
403 Err(ref x) => x.hash_stable(ctx, hasher),
408 impl<'a, T, CTX> HashStable<CTX> for &'a T
409 where T: HashStable<CTX> + ?Sized
412 fn hash_stable<W: StableHasherResult>(&self,
414 hasher: &mut StableHasher<W>) {
415 (**self).hash_stable(ctx, hasher);
419 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
421 fn hash_stable<W: StableHasherResult>(&self,
423 hasher: &mut StableHasher<W>) {
424 ::std::hash::Hash::hash(self, hasher);
428 impl<I: indexed_vec::Idx, T, CTX> HashStable<CTX> for indexed_vec::IndexVec<I, T>
429 where T: HashStable<CTX>,
431 fn hash_stable<W: StableHasherResult>(&self,
433 hasher: &mut StableHasher<W>) {
434 self.len().hash_stable(ctx, hasher);
436 v.hash_stable(ctx, hasher);
442 impl<I: indexed_vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I>
444 fn hash_stable<W: StableHasherResult>(&self,
446 hasher: &mut StableHasher<W>) {
447 self.words().hash_stable(ctx, hasher);
451 impl_stable_hash_via_hash!(::std::path::Path);
452 impl_stable_hash_via_hash!(::std::path::PathBuf);
454 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
455 where K: ToStableHashKey<HCX> + Eq + Hash,
460 fn hash_stable<W: StableHasherResult>(&self,
462 hasher: &mut StableHasher<W>) {
463 hash_stable_hashmap(hcx, hasher, self, ToStableHashKey::to_stable_hash_key);
467 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
468 where K: ToStableHashKey<HCX> + Eq + Hash,
471 fn hash_stable<W: StableHasherResult>(&self,
473 hasher: &mut StableHasher<W>) {
474 let mut keys: Vec<_> = self.iter()
475 .map(|k| k.to_stable_hash_key(hcx))
477 keys.sort_unstable();
478 keys.hash_stable(hcx, hasher);
482 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
483 where K: ToStableHashKey<HCX>,
486 fn hash_stable<W: StableHasherResult>(&self,
488 hasher: &mut StableHasher<W>) {
489 let mut entries: Vec<_> = self.iter()
490 .map(|(k, v)| (k.to_stable_hash_key(hcx), v))
492 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
493 entries.hash_stable(hcx, hasher);
497 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
498 where K: ToStableHashKey<HCX>,
500 fn hash_stable<W: StableHasherResult>(&self,
502 hasher: &mut StableHasher<W>) {
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, W>(
513 hasher: &mut StableHasher<W>,
514 map: &::std::collections::HashMap<K, V, R>,
515 to_stable_hash_key: F)
519 SK: HashStable<HCX> + Ord + Clone,
520 F: Fn(&K, &HCX) -> SK,
521 W: StableHasherResult,
523 let mut entries: Vec<_> = map.iter()
524 .map(|(k, v)| (to_stable_hash_key(k, hcx), v))
526 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
527 entries.hash_stable(hcx, hasher);
531 /// A vector container that makes sure that its items are hashed in a stable
533 pub struct StableVec<T>(Vec<T>);
535 impl<T> StableVec<T> {
536 pub fn new(v: Vec<T>) -> Self {
541 impl<T> ::std::ops::Deref for StableVec<T> {
542 type Target = Vec<T>;
544 fn deref(&self) -> &Vec<T> {
549 impl<T, HCX> HashStable<HCX> for StableVec<T>
550 where T: HashStable<HCX> + ToStableHashKey<HCX>
552 fn hash_stable<W: StableHasherResult>(&self,
554 hasher: &mut StableHasher<W>) {
555 let StableVec(ref v) = *self;
557 let mut sorted: Vec<_> = v.iter()
558 .map(|x| x.to_stable_hash_key(hcx))
560 sorted.sort_unstable();
561 sorted.hash_stable(hcx, hasher);