]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/fnv.rs
Auto merge of #31077 - nagisa:mir-temp-promotion, r=dotdash
[rust.git] / src / librustc_data_structures / fnv.rs
1 // Copyright 2015 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.
4 //
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.
10
11 use std::collections::{HashMap, HashSet};
12 use std::collections::hash_state::DefaultState;
13 use std::default::Default;
14 use std::hash::{Hasher, Hash};
15
16 pub type FnvHashMap<K, V> = HashMap<K, V, DefaultState<FnvHasher>>;
17 pub type FnvHashSet<V> = HashSet<V, DefaultState<FnvHasher>>;
18
19 #[allow(non_snake_case)]
20 pub fn FnvHashMap<K: Hash + Eq, V>() -> FnvHashMap<K, V> {
21     Default::default()
22 }
23
24 #[allow(non_snake_case)]
25 pub fn FnvHashSet<V: Hash + Eq>() -> FnvHashSet<V> {
26     Default::default()
27 }
28
29 /// A speedy hash algorithm for node ids and def ids. The hashmap in
30 /// libcollections by default uses SipHash which isn't quite as speedy as we
31 /// want. In the compiler we're not really worried about DOS attempts, so we
32 /// just default to a non-cryptographic hash.
33 ///
34 /// This uses FNV hashing, as described here:
35 /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
36 pub struct FnvHasher(u64);
37
38 impl Default for FnvHasher {
39     fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) }
40 }
41
42 impl Hasher for FnvHasher {
43     fn write(&mut self, bytes: &[u8]) {
44         let FnvHasher(mut hash) = *self;
45         for byte in bytes {
46             hash = hash ^ (*byte as u64);
47             hash = hash.wrapping_mul(0x100000001b3);
48         }
49         *self = FnvHasher(hash);
50     }
51     fn finish(&self) -> u64 { self.0 }
52 }