1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::hash::{Hash, Hasher, BuildHasher};
12 use std::marker::PhantomData;
14 use sip128::SipHasher128;
16 /// When hashing something that ends up affecting properties like symbol names,
17 /// we want these symbol names to be calculated independently of other factors
18 /// like what architecture you're compiling *from*.
20 /// To that end we always convert integers to little-endian format before
21 /// hashing and the architecture dependent `isize` and `usize` types are
22 /// extended to 64 bits if needed.
23 pub struct StableHasher<W> {
26 width: PhantomData<W>,
29 impl<W: StableHasherResult> ::std::fmt::Debug for StableHasher<W> {
30 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
31 write!(f, "{:?}", self.state)
35 pub trait StableHasherResult: Sized {
36 fn finish(hasher: StableHasher<Self>) -> Self;
39 impl<W: StableHasherResult> StableHasher<W> {
40 pub fn new() -> Self {
42 state: SipHasher128::new_with_keys(0, 0),
48 pub fn finish(self) -> W {
53 impl StableHasherResult for u128 {
54 fn finish(hasher: StableHasher<Self>) -> Self {
55 let (_0, _1) = hasher.finalize();
56 (_0 as u128) | ((_1 as u128) << 64)
60 impl StableHasherResult for u64 {
61 fn finish(hasher: StableHasher<Self>) -> Self {
66 impl<W> StableHasher<W> {
68 pub fn finalize(self) -> (u64, u64) {
69 self.state.finish128()
73 pub fn bytes_hashed(&self) -> u64 {
78 impl<W> Hasher for StableHasher<W> {
79 fn finish(&self) -> u64 {
80 panic!("use StableHasher::finalize instead");
84 fn write(&mut self, bytes: &[u8]) {
85 self.state.write(bytes);
86 self.bytes_hashed += bytes.len() as u64;
90 fn write_u8(&mut self, i: u8) {
91 self.state.write_u8(i);
92 self.bytes_hashed += 1;
96 fn write_u16(&mut self, i: u16) {
97 self.state.write_u16(i.to_le());
98 self.bytes_hashed += 2;
102 fn write_u32(&mut self, i: u32) {
103 self.state.write_u32(i.to_le());
104 self.bytes_hashed += 4;
108 fn write_u64(&mut self, i: u64) {
109 self.state.write_u64(i.to_le());
110 self.bytes_hashed += 8;
114 fn write_u128(&mut self, i: u128) {
115 self.state.write_u128(i.to_le());
116 self.bytes_hashed += 16;
120 fn write_usize(&mut self, i: usize) {
121 // Always treat usize as u64 so we get the same results on 32 and 64 bit
122 // platforms. This is important for symbol hashes when cross compiling,
124 self.state.write_u64((i as u64).to_le());
125 self.bytes_hashed += 8;
129 fn write_i8(&mut self, i: i8) {
130 self.state.write_i8(i);
131 self.bytes_hashed += 1;
135 fn write_i16(&mut self, i: i16) {
136 self.state.write_i16(i.to_le());
137 self.bytes_hashed += 2;
141 fn write_i32(&mut self, i: i32) {
142 self.state.write_i32(i.to_le());
143 self.bytes_hashed += 4;
147 fn write_i64(&mut self, i: i64) {
148 self.state.write_i64(i.to_le());
149 self.bytes_hashed += 8;
153 fn write_i128(&mut self, i: i128) {
154 self.state.write_i128(i.to_le());
155 self.bytes_hashed += 16;
159 fn write_isize(&mut self, i: isize) {
160 // Always treat isize as i64 so we get the same results on 32 and 64 bit
161 // platforms. This is important for symbol hashes when cross compiling,
163 self.state.write_i64((i as i64).to_le());
164 self.bytes_hashed += 8;
168 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
169 /// stable across multiple compilation sessions.
170 pub trait HashStable<CTX> {
171 fn hash_stable<W: StableHasherResult>(&self,
173 hasher: &mut StableHasher<W>);
176 /// Implement this for types that can be turned into stable keys like, for
177 /// example, for DefId that can be converted to a DefPathHash. This is used for
178 /// bringing maps into a predictable order before hashing them.
179 pub trait ToStableHashKey<HCX> {
180 type KeyType: Ord + Clone + Sized + HashStable<HCX>;
181 fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
184 // Implement HashStable by just calling `Hash::hash()`. This works fine for
185 // self-contained values that don't depend on the hashing context `CTX`.
187 macro_rules! impl_stable_hash_via_hash {
189 impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
191 fn hash_stable<W: $crate::stable_hasher::StableHasherResult>(
194 hasher: &mut $crate::stable_hasher::StableHasher<W>
196 ::std::hash::Hash::hash(self, hasher);
202 impl_stable_hash_via_hash!(i8);
203 impl_stable_hash_via_hash!(i16);
204 impl_stable_hash_via_hash!(i32);
205 impl_stable_hash_via_hash!(i64);
206 impl_stable_hash_via_hash!(isize);
208 impl_stable_hash_via_hash!(u8);
209 impl_stable_hash_via_hash!(u16);
210 impl_stable_hash_via_hash!(u32);
211 impl_stable_hash_via_hash!(u64);
212 impl_stable_hash_via_hash!(usize);
214 impl_stable_hash_via_hash!(u128);
215 impl_stable_hash_via_hash!(i128);
217 impl_stable_hash_via_hash!(char);
218 impl_stable_hash_via_hash!(());
220 impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
221 fn hash_stable<W: StableHasherResult>(&self,
223 hasher: &mut StableHasher<W>) {
224 self.get().hash_stable(ctx, hasher)
228 impl<CTX> HashStable<CTX> for f32 {
229 fn hash_stable<W: StableHasherResult>(&self,
231 hasher: &mut StableHasher<W>) {
232 let val: u32 = unsafe {
233 ::std::mem::transmute(*self)
235 val.hash_stable(ctx, hasher);
239 impl<CTX> HashStable<CTX> for f64 {
240 fn hash_stable<W: StableHasherResult>(&self,
242 hasher: &mut StableHasher<W>) {
243 let val: u64 = unsafe {
244 ::std::mem::transmute(*self)
246 val.hash_stable(ctx, hasher);
250 impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
251 fn hash_stable<W: StableHasherResult>(&self,
253 hasher: &mut StableHasher<W>) {
254 (*self as i8).hash_stable(ctx, hasher);
258 impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
259 fn hash_stable<W: StableHasherResult>(&self,
261 hasher: &mut StableHasher<W>) {
262 let (ref _0,) = *self;
263 _0.hash_stable(ctx, hasher);
267 impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
268 fn hash_stable<W: StableHasherResult>(&self,
270 hasher: &mut StableHasher<W>) {
271 let (ref _0, ref _1) = *self;
272 _0.hash_stable(ctx, hasher);
273 _1.hash_stable(ctx, hasher);
277 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
278 where T1: HashStable<CTX>,
282 fn hash_stable<W: StableHasherResult>(&self,
284 hasher: &mut StableHasher<W>) {
285 let (ref _0, ref _1, ref _2) = *self;
286 _0.hash_stable(ctx, hasher);
287 _1.hash_stable(ctx, hasher);
288 _2.hash_stable(ctx, hasher);
292 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
293 where T1: HashStable<CTX>,
298 fn hash_stable<W: StableHasherResult>(&self,
300 hasher: &mut StableHasher<W>) {
301 let (ref _0, ref _1, ref _2, ref _3) = *self;
302 _0.hash_stable(ctx, hasher);
303 _1.hash_stable(ctx, hasher);
304 _2.hash_stable(ctx, hasher);
305 _3.hash_stable(ctx, hasher);
309 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
310 default fn hash_stable<W: StableHasherResult>(&self,
312 hasher: &mut StableHasher<W>) {
313 self.len().hash_stable(ctx, hasher);
315 item.hash_stable(ctx, hasher);
320 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<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 Box<T> {
331 fn hash_stable<W: StableHasherResult>(&self,
333 hasher: &mut StableHasher<W>) {
334 (**self).hash_stable(ctx, hasher);
338 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
340 fn hash_stable<W: StableHasherResult>(&self,
342 hasher: &mut StableHasher<W>) {
343 (**self).hash_stable(ctx, hasher);
347 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
349 fn hash_stable<W: StableHasherResult>(&self,
351 hasher: &mut StableHasher<W>) {
352 (**self).hash_stable(ctx, hasher);
356 impl<CTX> HashStable<CTX> for str {
358 fn hash_stable<W: StableHasherResult>(&self,
360 hasher: &mut StableHasher<W>) {
361 self.len().hash(hasher);
362 self.as_bytes().hash(hasher);
367 impl<CTX> HashStable<CTX> for String {
369 fn hash_stable<W: StableHasherResult>(&self,
371 hasher: &mut StableHasher<W>) {
372 (&self[..]).hash_stable(hcx, hasher);
376 impl<HCX> ToStableHashKey<HCX> for String {
377 type KeyType = String;
379 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
384 impl<CTX> HashStable<CTX> for bool {
386 fn hash_stable<W: StableHasherResult>(&self,
388 hasher: &mut StableHasher<W>) {
389 (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
394 impl<T, CTX> HashStable<CTX> for Option<T>
395 where T: HashStable<CTX>
398 fn hash_stable<W: StableHasherResult>(&self,
400 hasher: &mut StableHasher<W>) {
401 if let Some(ref value) = *self {
402 1u8.hash_stable(ctx, hasher);
403 value.hash_stable(ctx, hasher);
405 0u8.hash_stable(ctx, hasher);
410 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
411 where T1: HashStable<CTX>,
415 fn hash_stable<W: StableHasherResult>(&self,
417 hasher: &mut StableHasher<W>) {
418 mem::discriminant(self).hash_stable(ctx, hasher);
420 Ok(ref x) => x.hash_stable(ctx, hasher),
421 Err(ref x) => x.hash_stable(ctx, hasher),
426 impl<'a, T, CTX> HashStable<CTX> for &'a T
427 where T: HashStable<CTX> + ?Sized
430 fn hash_stable<W: StableHasherResult>(&self,
432 hasher: &mut StableHasher<W>) {
433 (**self).hash_stable(ctx, hasher);
437 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
439 fn hash_stable<W: StableHasherResult>(&self,
441 hasher: &mut StableHasher<W>) {
442 ::std::hash::Hash::hash(self, hasher);
446 impl<I: ::indexed_vec::Idx, T, CTX> HashStable<CTX> for ::indexed_vec::IndexVec<I, T>
447 where T: HashStable<CTX>,
449 fn hash_stable<W: StableHasherResult>(&self,
451 hasher: &mut StableHasher<W>) {
452 self.len().hash_stable(ctx, hasher);
454 v.hash_stable(ctx, hasher);
460 impl<I: ::indexed_vec::Idx, CTX> HashStable<CTX> for ::bit_set::BitSet<I>
462 fn hash_stable<W: StableHasherResult>(&self,
464 hasher: &mut StableHasher<W>) {
465 self.words().hash_stable(ctx, hasher);
469 impl_stable_hash_via_hash!(::std::path::Path);
470 impl_stable_hash_via_hash!(::std::path::PathBuf);
472 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
473 where K: ToStableHashKey<HCX> + Eq + Hash,
478 fn hash_stable<W: StableHasherResult>(&self,
480 hasher: &mut StableHasher<W>) {
481 hash_stable_hashmap(hcx, hasher, self, ToStableHashKey::to_stable_hash_key);
485 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
486 where K: ToStableHashKey<HCX> + Eq + Hash,
489 fn hash_stable<W: StableHasherResult>(&self,
491 hasher: &mut StableHasher<W>) {
492 let mut keys: Vec<_> = self.iter()
493 .map(|k| k.to_stable_hash_key(hcx))
495 keys.sort_unstable();
496 keys.hash_stable(hcx, hasher);
500 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
501 where K: ToStableHashKey<HCX>,
504 fn hash_stable<W: StableHasherResult>(&self,
506 hasher: &mut StableHasher<W>) {
507 let mut entries: Vec<_> = self.iter()
508 .map(|(k, v)| (k.to_stable_hash_key(hcx), v))
510 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
511 entries.hash_stable(hcx, hasher);
515 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
516 where K: ToStableHashKey<HCX>,
518 fn hash_stable<W: StableHasherResult>(&self,
520 hasher: &mut StableHasher<W>) {
521 let mut keys: Vec<_> = self.iter()
522 .map(|k| k.to_stable_hash_key(hcx))
524 keys.sort_unstable();
525 keys.hash_stable(hcx, hasher);
529 pub fn hash_stable_hashmap<HCX, K, V, R, SK, F, W>(
531 hasher: &mut StableHasher<W>,
532 map: &::std::collections::HashMap<K, V, R>,
533 to_stable_hash_key: F)
537 SK: HashStable<HCX> + Ord + Clone,
538 F: Fn(&K, &HCX) -> SK,
539 W: StableHasherResult,
541 let mut entries: Vec<_> = map.iter()
542 .map(|(k, v)| (to_stable_hash_key(k, hcx), v))
544 entries.sort_unstable_by(|&(ref sk1, _), &(ref sk2, _)| sk1.cmp(sk2));
545 entries.hash_stable(hcx, hasher);
549 /// A vector container that makes sure that its items are hashed in a stable
551 pub struct StableVec<T>(Vec<T>);
553 impl<T> StableVec<T> {
554 pub fn new(v: Vec<T>) -> Self {
559 impl<T> ::std::ops::Deref for StableVec<T> {
560 type Target = Vec<T>;
562 fn deref(&self) -> &Vec<T> {
567 impl<T, HCX> HashStable<HCX> for StableVec<T>
568 where T: HashStable<HCX> + ToStableHashKey<HCX>
570 fn hash_stable<W: StableHasherResult>(&self,
572 hasher: &mut StableHasher<W>) {
573 let StableVec(ref v) = *self;
575 let mut sorted: Vec<_> = v.iter()
576 .map(|x| x.to_stable_hash_key(hcx))
578 sorted.sort_unstable();
579 sorted.hash_stable(hcx, hasher);