1 // Copyright 2014 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 //! An efficient hash map for node IDs
13 #![allow(non_snake_case)]
15 use std::collections::hash_state::{DefaultState};
16 use std::collections::{HashMap, HashSet};
17 use std::default::Default;
18 use std::hash::{Hasher, Writer, Hash};
21 pub type FnvHashMap<K, V> = HashMap<K, V, DefaultState<FnvHasher>>;
22 pub type FnvHashSet<V> = HashSet<V, DefaultState<FnvHasher>>;
24 pub type NodeMap<T> = FnvHashMap<ast::NodeId, T>;
25 pub type DefIdMap<T> = FnvHashMap<ast::DefId, T>;
27 pub type NodeSet = FnvHashSet<ast::NodeId>;
28 pub type DefIdSet = FnvHashSet<ast::DefId>;
30 pub fn FnvHashMap<K: Hash<FnvHasher> + Eq, V>() -> FnvHashMap<K, V> {
33 pub fn FnvHashSet<V: Hash<FnvHasher> + Eq>() -> FnvHashSet<V> {
37 pub fn NodeMap<T>() -> NodeMap<T> { FnvHashMap() }
38 pub fn DefIdMap<T>() -> DefIdMap<T> { FnvHashMap() }
39 pub fn NodeSet() -> NodeSet { FnvHashSet() }
40 pub fn DefIdSet() -> DefIdSet { FnvHashSet() }
42 /// A speedy hash algorithm for node ids and def ids. The hashmap in
43 /// libcollections by default uses SipHash which isn't quite as speedy as we
44 /// want. In the compiler we're not really worried about DOS attempts, so we
45 /// just default to a non-cryptographic hash.
47 /// This uses FNV hashing, as described here:
48 /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
49 pub struct FnvHasher(u64);
51 impl Default for FnvHasher {
52 fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) }
55 impl Hasher for FnvHasher {
57 fn reset(&mut self) { *self = Default::default(); }
58 fn finish(&self) -> u64 { self.0 }
61 impl Writer for FnvHasher {
62 fn write(&mut self, bytes: &[u8]) {
63 let FnvHasher(mut hash) = *self;
65 hash = hash ^ (*byte as u64);
66 hash = hash * 0x100000001b3;
68 *self = FnvHasher(hash);