fasthash_fork/
sea.rs

1//! `SeaHash`: A bizarrely fast hash function.
2//!
3//! by ticki <ticki@users.noreply.github.com>
4//!
5//! `SeaHash` is a hash function with performance better than
6//! (around 3-20% improvement) xxHash and `MetroHash`.
7//! Furthermore, `SeaHash` has mathematically provable statistical guarantees.
8//!
9//!
10//! # Example
11//!
12//! ```
13//! use std::hash::{Hash, Hasher};
14//!
15//! use fasthash::{sea, SeaHasher};
16//!
17//! fn hash<T: Hash>(t: &T) -> u64 {
18//!     let mut s: SeaHasher = Default::default();
19//!     t.hash(&mut s);
20//!     s.finish()
21//! }
22//!
23//! assert_eq!(sea::hash64(b"hello world\xff"), 8985868041853666652);
24//!
25//! assert_eq!(hash(&"hello world"), 8985868041853666652);
26//! ```
27//!
28pub use seahash::{hash as hash64, hash_seeded as hash64_with_seeds, SeaHasher as Hasher64};
29
30use crate::hasher::{FastHash, FastHasher, StreamHasher};
31
32/// `SeaHash` 64-bit hash functions
33///
34/// # Example
35///
36/// ```
37/// use fasthash::{sea::Hash64, FastHash};
38///
39/// assert_eq!(Hash64::hash(b"hello"), 153251464476911497);
40/// assert_eq!(
41///     Hash64::hash_with_seed(b"hello", (12, 34, 56, 78)),
42///     3117749726954423822
43/// );
44/// assert_eq!(Hash64::hash(b"helloworld"), 9532038143498849405);
45/// ```
46#[derive(Clone, Default)]
47pub struct Hash64;
48
49impl FastHash for Hash64 {
50    type Hash = u64;
51    type Seed = (u64, u64, u64, u64);
52
53    #[inline(always)]
54    fn hash<T: AsRef<[u8]>>(bytes: T) -> u64 {
55        seahash::hash(bytes.as_ref())
56    }
57
58    #[inline(always)]
59    fn hash_with_seed<T: AsRef<[u8]>>(bytes: T, seed: (u64, u64, u64, u64)) -> u64 {
60        seahash::hash_seeded(bytes.as_ref(), seed.0, seed.1, seed.2, seed.3)
61    }
62}
63
64impl_build_hasher!(Hasher64, Hash64);
65
66impl FastHasher for Hasher64 {
67    type Seed = (u64, u64, u64, u64);
68    type Output = u64;
69
70    #[inline(always)]
71    fn new() -> Self {
72        Hasher64::new()
73    }
74
75    #[inline(always)]
76    fn with_seed(seed: Self::Seed) -> Self {
77        Hasher64::with_seeds(seed.0, seed.1, seed.2, seed.3)
78    }
79}
80
81impl StreamHasher for Hasher64 {}
82
83#[cfg(test)]
84mod tests {
85    use std::hash::Hasher;
86
87    use super::Hasher64;
88
89    #[test]
90    fn test_seahash64() {
91        let mut h = Hasher64::new();
92
93        h.write(b"hello");
94        assert_eq!(h.finish(), 153251464476911497);
95
96        h.write(b"world");
97        assert_eq!(h.finish(), 9532038143498849405);
98    }
99}