1
use std::hash::BuildHasher;
2
use std::hash::Hasher;
3

            
4
/// A hasher that directly uses the value provided to write_u64 as the hash
5
pub struct NoHasher(u64);
6

            
7
impl Hasher for NoHasher {
8
    /// Returns the current value as the hash
9
538833143
    fn finish(&self) -> u64 {
10
538833143
        self.0
11
538833143
    }
12

            
13
    fn write(&mut self, _bytes: &[u8]) {
14
        // This implementation only supports write_u64
15
        debug_assert!(false, "NoHasher only supports write_u64");
16
    }
17

            
18
538833142
    fn write_u64(&mut self, i: u64) {
19
538833142
        self.0 = i;
20
538833142
    }
21
}
22

            
23
/// A builder for NoHasher. Starts with a hash of 0 and returns whatever value is passed to write_u64
24
#[derive(Default)]
25
pub struct NoHasherBuilder;
26

            
27
impl BuildHasher for NoHasherBuilder {
28
    type Hasher = NoHasher;
29

            
30
538833142
    fn build_hasher(&self) -> Self::Hasher {
31
538833142
        NoHasher(0)
32
538833142
    }
33
}
34

            
35
#[cfg(test)]
36
mod tests {
37
    use super::*;
38

            
39
    #[test]
40
1
    fn test_no_hasher() {
41
1
        let mut hasher = NoHasher(0);
42
1
        hasher.write_u64(42);
43
1
        assert_eq!(
44
1
            hasher.finish(),
45
            42,
46
            "NoHasher should return the value passed to write_u64"
47
        );
48

            
49
1
        let builder = NoHasherBuilder;
50
1
        let hasher = builder.build_hasher();
51
1
        assert_eq!(
52
1
            hasher.finish(),
53
            0,
54
            "NoHasherBuilder should create a hasher with initial value 0"
55
        );
56
1
    }
57
}