foyer_common/
hasher.rs

1// Copyright 2025 foyer Project Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::hash::{BuildHasher, Hasher};
16
17pub use ahash::RandomState as AhashRandomState;
18
19/// A hasher return u64 mod result.
20#[derive(Debug, Default)]
21pub struct ModRandomState {
22    state: u64,
23}
24
25impl Hasher for ModRandomState {
26    fn finish(&self) -> u64 {
27        self.state
28    }
29
30    fn write(&mut self, bytes: &[u8]) {
31        for byte in bytes {
32            self.state = (self.state << 8) + *byte as u64;
33        }
34    }
35
36    fn write_u8(&mut self, i: u8) {
37        self.write(&[i])
38    }
39
40    fn write_u16(&mut self, i: u16) {
41        self.write(&i.to_be_bytes())
42    }
43
44    fn write_u32(&mut self, i: u32) {
45        self.write(&i.to_be_bytes())
46    }
47
48    fn write_u64(&mut self, i: u64) {
49        self.write(&i.to_be_bytes())
50    }
51
52    fn write_u128(&mut self, i: u128) {
53        self.write(&i.to_be_bytes())
54    }
55
56    fn write_usize(&mut self, i: usize) {
57        self.write(&i.to_be_bytes())
58    }
59
60    fn write_i8(&mut self, i: i8) {
61        self.write_u8(i as u8)
62    }
63
64    fn write_i16(&mut self, i: i16) {
65        self.write_u16(i as u16)
66    }
67
68    fn write_i32(&mut self, i: i32) {
69        self.write_u32(i as u32)
70    }
71
72    fn write_i64(&mut self, i: i64) {
73        self.write_u64(i as u64)
74    }
75
76    fn write_i128(&mut self, i: i128) {
77        self.write_u128(i as u128)
78    }
79
80    fn write_isize(&mut self, i: isize) {
81        self.write_usize(i as usize)
82    }
83}
84
85impl BuildHasher for ModRandomState {
86    type Hasher = Self;
87
88    fn build_hasher(&self) -> Self::Hasher {
89        Self::default()
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn test_mod_hasher() {
99        for i in 0..255u8 {
100            assert_eq!(i, ModRandomState::default().hash_one(i) as u8,)
101        }
102    }
103}