foyer_common/
hasher.rs

1// Copyright 2026 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
17/// A hasher return u64 mod result.
18#[derive(Debug, Default)]
19pub struct ModHasher {
20    state: u64,
21}
22
23impl Hasher for ModHasher {
24    fn finish(&self) -> u64 {
25        self.state
26    }
27
28    fn write(&mut self, bytes: &[u8]) {
29        for byte in bytes {
30            self.state = (self.state << 8) + *byte as u64;
31        }
32    }
33
34    fn write_u8(&mut self, i: u8) {
35        self.write(&[i])
36    }
37
38    fn write_u16(&mut self, i: u16) {
39        self.write(&i.to_be_bytes())
40    }
41
42    fn write_u32(&mut self, i: u32) {
43        self.write(&i.to_be_bytes())
44    }
45
46    fn write_u64(&mut self, i: u64) {
47        self.write(&i.to_be_bytes())
48    }
49
50    fn write_u128(&mut self, i: u128) {
51        self.write(&i.to_be_bytes())
52    }
53
54    fn write_usize(&mut self, i: usize) {
55        self.write(&i.to_be_bytes())
56    }
57
58    fn write_i8(&mut self, i: i8) {
59        self.write_u8(i as u8)
60    }
61
62    fn write_i16(&mut self, i: i16) {
63        self.write_u16(i as u16)
64    }
65
66    fn write_i32(&mut self, i: i32) {
67        self.write_u32(i as u32)
68    }
69
70    fn write_i64(&mut self, i: i64) {
71        self.write_u64(i as u64)
72    }
73
74    fn write_i128(&mut self, i: i128) {
75        self.write_u128(i as u128)
76    }
77
78    fn write_isize(&mut self, i: isize) {
79        self.write_usize(i as usize)
80    }
81}
82
83impl BuildHasher for ModHasher {
84    type Hasher = Self;
85
86    fn build_hasher(&self) -> Self::Hasher {
87        Self::default()
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    #[test]
96    fn test_mod_hasher() {
97        for i in 0..255u8 {
98            assert_eq!(i, ModHasher::default().hash_one(i) as u8,)
99        }
100    }
101}