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.
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::collections::{HashMap, HashSet};
12 use std::default::Default;
13 use std::hash::{Hasher, Hash, BuildHasherDefault};
16 pub type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
17 pub type FxHashSet<V> = HashSet<V, BuildHasherDefault<FxHasher>>;
19 #[allow(non_snake_case)]
20 pub fn FxHashMap<K: Hash + Eq, V>() -> FxHashMap<K, V> {
24 #[allow(non_snake_case)]
25 pub fn FxHashSet<V: Hash + Eq>() -> FxHashSet<V> {
29 /// A speedy hash algorithm for use within rustc. The hashmap in libcollections
30 /// by default uses SipHash which isn't quite as speedy as we want. In the
31 /// compiler we're not really worried about DOS attempts, so we use a fast
32 /// non-cryptographic hash.
34 /// This is the same as the algorithm used by Firefox -- which is a homespun
35 /// one not based on any widely-known algorithm -- though modified to produce
36 /// 64-bit hash values instead of 32-bit hash values. It consistently
37 /// out-performs an FNV-based hash within rustc itself -- the collision rate is
38 /// similar or slightly worse than FNV, but the speed of the hash function
39 /// itself is much higher because it works on up to 8 bytes at a time.
44 #[cfg(target_pointer_width = "32")]
45 const K: usize = 0x9e3779b9;
46 #[cfg(target_pointer_width = "64")]
47 const K: usize = 0x517cc1b727220a95;
49 impl Default for FxHasher {
51 fn default() -> FxHasher {
58 fn add_to_hash(&mut self, i: usize) {
59 self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K);
63 impl Hasher for FxHasher {
65 fn write(&mut self, bytes: &[u8]) {
68 self.add_to_hash(i as usize);
73 fn write_u8(&mut self, i: u8) {
74 self.add_to_hash(i as usize);
78 fn write_u16(&mut self, i: u16) {
79 self.add_to_hash(i as usize);
83 fn write_u32(&mut self, i: u32) {
84 self.add_to_hash(i as usize);
87 #[cfg(target_pointer_width = "32")]
89 fn write_u64(&mut self, i: u64) {
90 self.add_to_hash(i as usize);
91 self.add_to_hash((i >> 32) as usize);
94 #[cfg(target_pointer_width = "64")]
96 fn write_u64(&mut self, i: u64) {
97 self.add_to_hash(i as usize);
101 fn write_usize(&mut self, i: usize) {
106 fn finish(&self) -> u64 {
111 pub fn hash<T: Hash>(v: &T) -> u64 {
112 let mut state = FxHasher::default();