]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/nodemap.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / librustc / util / nodemap.rs
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.
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 //! An efficient hash map for node IDs
12
13 #![allow(non_snake_case)]
14
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};
19 use syntax::ast;
20
21 pub type FnvHashMap<K, V> = HashMap<K, V, DefaultState<FnvHasher>>;
22 pub type FnvHashSet<V> = HashSet<V, DefaultState<FnvHasher>>;
23
24 pub type NodeMap<T> = FnvHashMap<ast::NodeId, T>;
25 pub type DefIdMap<T> = FnvHashMap<ast::DefId, T>;
26
27 pub type NodeSet = FnvHashSet<ast::NodeId>;
28 pub type DefIdSet = FnvHashSet<ast::DefId>;
29
30 pub fn FnvHashMap<K: Hash<FnvHasher> + Eq, V>() -> FnvHashMap<K, V> {
31     Default::default()
32 }
33 pub fn FnvHashSet<V: Hash<FnvHasher> + Eq>() -> FnvHashSet<V> {
34     Default::default()
35 }
36
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() }
41
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.
46 ///
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);
50
51 impl Default for FnvHasher {
52     fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) }
53 }
54
55 impl Hasher for FnvHasher {
56     type Output = u64;
57     fn reset(&mut self) { *self = Default::default(); }
58     fn finish(&self) -> u64 { self.0 }
59 }
60
61 impl Writer for FnvHasher {
62     fn write(&mut self, bytes: &[u8]) {
63         let FnvHasher(mut hash) = *self;
64         for byte in bytes {
65             hash = hash ^ (*byte as u64);
66             hash = hash * 0x100000001b3;
67         }
68         *self = FnvHasher(hash);
69     }
70 }