rune/runtime/
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
use core::hash::{BuildHasher, Hasher as _};

use rune_alloc::hash_map;

use crate as rune;
use crate::Any;

/// The default hasher used in Rune.
#[derive(Any)]
#[rune(item = ::std::hash)]
pub struct Hasher {
    hasher: hash_map::Hasher,
}

impl Hasher {
    /// Construct a new empty hasher.
    pub(crate) fn new_with<S>(build_hasher: &S) -> Self
    where
        S: BuildHasher<Hasher = hash_map::Hasher>,
    {
        Self {
            hasher: build_hasher.build_hasher(),
        }
    }

    /// Hash a string.
    pub(crate) fn write_str(&mut self, string: &str) {
        self.hasher.write(string.as_bytes());
    }

    /// Construct a hash.
    pub fn finish(&self) -> u64 {
        self.hasher.finish()
    }
}

impl core::hash::Hasher for Hasher {
    #[inline]
    fn finish(&self) -> u64 {
        self.hasher.finish()
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        self.hasher.write(bytes);
    }
}