hashbrown/
hasher.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#[cfg(feature = "default-hasher")]
use {
    core::hash::{BuildHasher, Hasher},
    foldhash::fast::RandomState,
};

/// Default hash builder for the `S` type parameter of
/// [`HashMap`](crate::HashMap) and [`HashSet`](crate::HashSet).
///
/// This only implements `BuildHasher` when the "default-hasher" crate feature
/// is enabled; otherwise it just serves as a placeholder, and a custom `S` type
/// must be used to have a fully functional `HashMap` or `HashSet`.
#[derive(Clone, Debug, Default)]
pub struct DefaultHashBuilder {
    #[cfg(feature = "default-hasher")]
    inner: RandomState,
}

#[cfg(feature = "default-hasher")]
impl BuildHasher for DefaultHashBuilder {
    type Hasher = DefaultHasher;

    #[inline(always)]
    fn build_hasher(&self) -> Self::Hasher {
        DefaultHasher {
            inner: self.inner.build_hasher(),
        }
    }
}

/// Default hasher for [`HashMap`](crate::HashMap) and [`HashSet`](crate::HashSet).
#[cfg(feature = "default-hasher")]
#[derive(Clone)]
pub struct DefaultHasher {
    inner: <RandomState as BuildHasher>::Hasher,
}

#[cfg(feature = "default-hasher")]
macro_rules! forward_writes {
    ($( $write:ident ( $ty:ty ) , )*) => {$(
        #[inline(always)]
        fn $write(&mut self, arg: $ty) {
            self.inner.$write(arg);
        }
    )*}
}

#[cfg(feature = "default-hasher")]
impl Hasher for DefaultHasher {
    forward_writes! {
        write(&[u8]),
        write_u8(u8),
        write_u16(u16),
        write_u32(u32),
        write_u64(u64),
        write_u128(u128),
        write_usize(usize),
        write_i8(i8),
        write_i16(i16),
        write_i32(i32),
        write_i64(i64),
        write_i128(i128),
        write_isize(isize),
    }

    // feature(hasher_prefixfree_extras)
    #[cfg(feature = "nightly")]
    forward_writes! {
        write_length_prefix(usize),
        write_str(&str),
    }

    #[inline(always)]
    fn finish(&self) -> u64 {
        self.inner.finish()
    }
}