rune/runtime/
hasher.rs

1use core::hash::{BuildHasher, Hasher as _};
2
3use rune_alloc::hash_map;
4
5use crate as rune;
6use crate::Any;
7
8/// The default hasher used in Rune.
9#[derive(Any)]
10#[rune(item = ::std::hash)]
11pub struct Hasher {
12    hasher: hash_map::Hasher,
13}
14
15impl Hasher {
16    /// Construct a new empty hasher.
17    pub(crate) fn new_with<S>(build_hasher: &S) -> Self
18    where
19        S: BuildHasher<Hasher = hash_map::Hasher>,
20    {
21        Self {
22            hasher: build_hasher.build_hasher(),
23        }
24    }
25
26    /// Hash a string.
27    pub(crate) fn write_str(&mut self, string: &str) {
28        self.hasher.write(string.as_bytes());
29    }
30
31    /// Construct a hash.
32    pub fn finish(&self) -> u64 {
33        self.hasher.finish()
34    }
35}
36
37impl core::hash::Hasher for Hasher {
38    #[inline]
39    fn finish(&self) -> u64 {
40        self.hasher.finish()
41    }
42
43    #[inline]
44    fn write(&mut self, bytes: &[u8]) {
45        self.hasher.write(bytes);
46    }
47}