rune/
hash.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
//! Utilities for working with hashes.

use crate::alloc::HashMap;

use core::hash::{BuildHasher, Hasher};

const SEED: u64 = 18446744073709551557u64;

#[doc(inline)]
pub use rune_core::hash::{Hash, IntoHash, ParametersBuilder, ToTypeHash, TooManyParameters};

/// A hash map suitable for storing values with hash keys.
pub(crate) type Map<T> = HashMap<Hash, T, HashBuildHasher>;

#[derive(Default, Clone, Copy)]
pub(crate) struct HashBuildHasher;

impl BuildHasher for HashBuildHasher {
    type Hasher = HashHasher;

    #[inline]
    fn build_hasher(&self) -> Self::Hasher {
        HashHasher(SEED)
    }
}

pub(crate) struct HashHasher(u64);

impl Hasher for HashHasher {
    #[inline]
    fn finish(&self) -> u64 {
        self.0
    }

    #[inline]
    fn write(&mut self, _: &[u8]) {
        panic!("Hash hashers assume that 64-bit hashes are already random")
    }

    #[inline]
    fn write_u64(&mut self, hash: u64) {
        self.0 ^= hash;
    }
}