foldhash/
lib.rs

1//! This crate provides foldhash, a fast, non-cryptographic, minimally
2//! DoS-resistant hashing algorithm designed for computational uses such as
3//! hashmaps, bloom filters, count sketching, etc.
4//!
5//! When should you **not** use foldhash:
6//!
7//! - You are afraid of people studying your long-running program's behavior
8//!   to reverse engineer its internal random state and using this knowledge to
9//!   create many colliding inputs for computational complexity attacks.
10//!
11//! - You expect foldhash to have a consistent output across versions or
12//!   platforms, such as for persistent file formats or communication protocols.
13//!   
14//! - You are relying on foldhash's properties for any kind of security.
15//!   Foldhash is **not appropriate for any cryptographic purpose**.
16//!
17//! Foldhash has two variants, one optimized for speed which is ideal for data
18//! structures such as hash maps and bloom filters, and one optimized for
19//! statistical quality which is ideal for algorithms such as
20//! [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) and
21//! [MinHash](https://en.wikipedia.org/wiki/MinHash).
22//!
23//! Foldhash can be used in a `#![no_std]` environment by disabling its default
24//! `"std"` feature.
25//!
26//! # Usage
27//!
28//! The easiest way to use this crate with the standard library [`HashMap`] or
29//! [`HashSet`] is to import them from `foldhash` instead, along with the
30//! extension traits to make [`HashMap::new`] and [`HashMap::with_capacity`]
31//! work out-of-the-box:
32//!
33//! ```rust
34//! use foldhash::{HashMap, HashMapExt};
35//!
36//! let mut hm = HashMap::new();
37//! hm.insert(42, "hello");
38//! ```
39//!
40//! You can also avoid the convenience types and do it manually by initializing
41//! a [`RandomState`](fast::RandomState), for example if you are using a different hash map
42//! implementation like [`hashbrown`](https://docs.rs/hashbrown/):
43//!
44//! ```rust
45//! use hashbrown::HashMap;
46//! use foldhash::fast::RandomState;
47//!
48//! let mut hm = HashMap::with_hasher(RandomState::default());
49//! hm.insert("foo", "bar");
50//! ```
51//!
52//! The above methods are the recommended way to use foldhash, which will
53//! automatically generate a randomly generated hasher instance for you. If you
54//! absolutely must have determinism you can use [`FixedState`](fast::FixedState)
55//! instead, but note that this makes you trivially vulnerable to HashDoS
56//! attacks and might lead to quadratic runtime when moving data from one
57//! hashmap/set into another:
58//!
59//! ```rust
60//! use std::collections::HashSet;
61//! use foldhash::fast::FixedState;
62//!
63//! let mut hm = HashSet::with_hasher(FixedState::with_seed(42));
64//! hm.insert([1, 10, 100]);
65//! ```
66//!
67//! If you rely on statistical properties of the hash for the correctness of
68//! your algorithm, such as in [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog),
69//! it is suggested to use the [`RandomState`](quality::RandomState)
70//! or [`FixedState`](quality::FixedState) from the [`quality`] module instead
71//! of the [`fast`] module. The latter is optimized purely for speed in hash
72//! tables and has known statistical imperfections.
73//!
74//! Finally, you can also directly use the [`RandomState`](quality::RandomState)
75//! or [`FixedState`](quality::FixedState) to manually hash items using the
76//! [`BuildHasher`](std::hash::BuildHasher) trait:
77//! ```rust
78//! use std::hash::BuildHasher;
79//! use foldhash::quality::RandomState;
80//!
81//! let random_state = RandomState::default();
82//! let hash = random_state.hash_one("hello world");
83//! ```
84
85#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
86#![warn(missing_docs)]
87
88use core::hash::Hasher;
89
90#[cfg(feature = "std")]
91mod convenience;
92mod seed;
93
94#[cfg(feature = "std")]
95pub use convenience::*;
96
97// Arbitrary constants with high entropy. Hexadecimal digits of pi were used.
98const ARBITRARY1: u64 = 0x243f6a8885a308d3;
99const ARBITRARY2: u64 = 0x13198a2e03707344;
100const ARBITRARY3: u64 = 0xa4093822299f31d0;
101const ARBITRARY4: u64 = 0x082efa98ec4e6c89;
102const ARBITRARY5: u64 = 0x452821e638d01377;
103const ARBITRARY6: u64 = 0xbe5466cf34e90c6c;
104const ARBITRARY7: u64 = 0xc0ac29b7c97c50dd;
105const ARBITRARY8: u64 = 0x3f84d5b5b5470917;
106const ARBITRARY9: u64 = 0x9216d5d98979fb1b;
107
108#[inline(always)]
109const fn folded_multiply(x: u64, y: u64) -> u64 {
110    #[cfg(target_pointer_width = "64")]
111    {
112        // We compute the full u64 x u64 -> u128 product, this is a single mul
113        // instruction on x86-64, one mul plus one mulhi on ARM64.
114        let full = (x as u128) * (y as u128);
115        let lo = full as u64;
116        let hi = (full >> 64) as u64;
117
118        // The middle bits of the full product fluctuate the most with small
119        // changes in the input. This is the top bits of lo and the bottom bits
120        // of hi. We can thus make the entire output fluctuate with small
121        // changes to the input by XOR'ing these two halves.
122        lo ^ hi
123    }
124
125    #[cfg(target_pointer_width = "32")]
126    {
127        // u64 x u64 -> u128 product is prohibitively expensive on 32-bit.
128        // Decompose into 32-bit parts.
129        let lx = x as u32;
130        let ly = y as u32;
131        let hx = (x >> 32) as u32;
132        let hy = (y >> 32) as u32;
133
134        // u32 x u32 -> u64 the low bits of one with the high bits of the other.
135        let afull = (lx as u64) * (hy as u64);
136        let bfull = (hx as u64) * (ly as u64);
137
138        // Combine, swapping low/high of one of them so the upper bits of the
139        // product of one combine with the lower bits of the other.
140        afull ^ bfull.rotate_right(32)
141    }
142}
143
144/// The foldhash implementation optimized for speed.
145pub mod fast {
146    use super::*;
147
148    pub use seed::fast::{FixedState, RandomState};
149
150    /// A [`Hasher`] instance implementing foldhash, optimized for speed.
151    ///
152    /// It can't be created directly, see [`RandomState`] or [`FixedState`].
153    #[derive(Clone)]
154    pub struct FoldHasher {
155        accumulator: u64,
156        sponge: u128,
157        sponge_len: u8,
158        fold_seed: u64,
159        expand_seed: u64,
160        expand_seed2: u64,
161        expand_seed3: u64,
162    }
163
164    impl FoldHasher {
165        pub(crate) fn with_seed(per_hasher_seed: u64, global_seed: &[u64; 4]) -> FoldHasher {
166            FoldHasher {
167                accumulator: per_hasher_seed,
168                sponge: 0,
169                sponge_len: 0,
170                fold_seed: global_seed[0],
171                expand_seed: global_seed[1],
172                expand_seed2: global_seed[2],
173                expand_seed3: global_seed[3],
174            }
175        }
176
177        #[inline(always)]
178        fn write_num<T: Into<u128>>(&mut self, x: T) {
179            let bits: usize = 8 * core::mem::size_of::<T>();
180            if self.sponge_len as usize + bits > 128 {
181                let lo = self.sponge as u64;
182                let hi = (self.sponge >> 64) as u64;
183                self.accumulator = folded_multiply(lo ^ self.accumulator, hi ^ self.fold_seed);
184                self.sponge = x.into();
185                self.sponge_len = 0;
186            } else {
187                self.sponge |= x.into() << self.sponge_len;
188                self.sponge_len += bits as u8;
189            }
190        }
191    }
192
193    impl Hasher for FoldHasher {
194        #[inline(always)]
195        fn write(&mut self, bytes: &[u8]) {
196            let mut s0 = self.accumulator;
197            let mut s1 = self.expand_seed;
198            let len = bytes.len();
199            if len <= 16 {
200                // XOR the input into s0, s1, then multiply and fold.
201                if len >= 8 {
202                    s0 ^= u64::from_ne_bytes(bytes[0..8].try_into().unwrap());
203                    s1 ^= u64::from_ne_bytes(bytes[len - 8..].try_into().unwrap());
204                } else if len >= 4 {
205                    s0 ^= u32::from_ne_bytes(bytes[0..4].try_into().unwrap()) as u64;
206                    s1 ^= u32::from_ne_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
207                } else if len > 0 {
208                    let lo = bytes[0];
209                    let mid = bytes[len / 2];
210                    let hi = bytes[len - 1];
211                    s0 ^= lo as u64;
212                    s1 ^= ((hi as u64) << 8) | mid as u64;
213                }
214                self.accumulator = folded_multiply(s0, s1);
215            } else if len < 256 {
216                self.accumulator = hash_bytes_medium(bytes, s0, s1, self.fold_seed);
217            } else {
218                self.accumulator = hash_bytes_long(
219                    bytes,
220                    s0,
221                    s1,
222                    self.expand_seed2,
223                    self.expand_seed3,
224                    self.fold_seed,
225                );
226            }
227        }
228
229        #[inline(always)]
230        fn write_u8(&mut self, i: u8) {
231            self.write_num(i);
232        }
233
234        #[inline(always)]
235        fn write_u16(&mut self, i: u16) {
236            self.write_num(i);
237        }
238
239        #[inline(always)]
240        fn write_u32(&mut self, i: u32) {
241            self.write_num(i);
242        }
243
244        #[inline(always)]
245        fn write_u64(&mut self, i: u64) {
246            self.write_num(i);
247        }
248
249        #[inline(always)]
250        fn write_u128(&mut self, i: u128) {
251            let lo = i as u64;
252            let hi = (i >> 64) as u64;
253            self.accumulator = folded_multiply(lo ^ self.accumulator, hi ^ self.fold_seed);
254        }
255
256        #[inline(always)]
257        fn write_usize(&mut self, i: usize) {
258            // u128 doesn't implement From<usize>.
259            #[cfg(target_pointer_width = "32")]
260            self.write_num(i as u32);
261            #[cfg(target_pointer_width = "64")]
262            self.write_num(i as u64);
263        }
264
265        #[inline(always)]
266        fn finish(&self) -> u64 {
267            if self.sponge_len > 0 {
268                let lo = self.sponge as u64;
269                let hi = (self.sponge >> 64) as u64;
270                folded_multiply(lo ^ self.accumulator, hi ^ self.fold_seed)
271            } else {
272                self.accumulator
273            }
274        }
275    }
276}
277
278/// The foldhash implementation optimized for quality.
279pub mod quality {
280    use super::*;
281
282    pub use seed::quality::{FixedState, RandomState};
283
284    /// A [`Hasher`] instance implementing foldhash, optimized for quality.
285    ///
286    /// It can't be created directly, see [`RandomState`] or [`FixedState`].
287    #[derive(Clone)]
288    pub struct FoldHasher {
289        pub(crate) inner: fast::FoldHasher,
290    }
291
292    impl Hasher for FoldHasher {
293        #[inline(always)]
294        fn write(&mut self, bytes: &[u8]) {
295            self.inner.write(bytes);
296        }
297
298        #[inline(always)]
299        fn write_u8(&mut self, i: u8) {
300            self.inner.write_u8(i);
301        }
302
303        #[inline(always)]
304        fn write_u16(&mut self, i: u16) {
305            self.inner.write_u16(i);
306        }
307
308        #[inline(always)]
309        fn write_u32(&mut self, i: u32) {
310            self.inner.write_u32(i);
311        }
312
313        #[inline(always)]
314        fn write_u64(&mut self, i: u64) {
315            self.inner.write_u64(i);
316        }
317
318        #[inline(always)]
319        fn write_u128(&mut self, i: u128) {
320            self.inner.write_u128(i);
321        }
322
323        #[inline(always)]
324        fn write_usize(&mut self, i: usize) {
325            self.inner.write_usize(i);
326        }
327
328        #[inline(always)]
329        fn finish(&self) -> u64 {
330            folded_multiply(self.inner.finish(), ARBITRARY1)
331        }
332    }
333}
334
335/// Hashes strings >= 16 bytes, has unspecified behavior when bytes.len() < 16.
336fn hash_bytes_medium(bytes: &[u8], mut s0: u64, mut s1: u64, fold_seed: u64) -> u64 {
337    // Process 32 bytes per iteration, 16 bytes from the start, 16 bytes from
338    // the end. On the last iteration these two chunks can overlap, but that is
339    // perfectly fine.
340    let left_to_right = bytes.chunks_exact(16);
341    let mut right_to_left = bytes.rchunks_exact(16);
342    for lo in left_to_right {
343        let hi = right_to_left.next().unwrap();
344        let unconsumed_start = lo.as_ptr();
345        let unconsumed_end = hi.as_ptr_range().end;
346        if unconsumed_start >= unconsumed_end {
347            break;
348        }
349
350        let a = u64::from_ne_bytes(lo[0..8].try_into().unwrap());
351        let b = u64::from_ne_bytes(lo[8..16].try_into().unwrap());
352        let c = u64::from_ne_bytes(hi[0..8].try_into().unwrap());
353        let d = u64::from_ne_bytes(hi[8..16].try_into().unwrap());
354        s0 = folded_multiply(a ^ s0, c ^ fold_seed);
355        s1 = folded_multiply(b ^ s1, d ^ fold_seed);
356    }
357
358    s0 ^ s1
359}
360
361/// Hashes strings >= 16 bytes, has unspecified behavior when bytes.len() < 16.
362#[cold]
363#[inline(never)]
364fn hash_bytes_long(
365    bytes: &[u8],
366    mut s0: u64,
367    mut s1: u64,
368    mut s2: u64,
369    mut s3: u64,
370    fold_seed: u64,
371) -> u64 {
372    let chunks = bytes.chunks_exact(64);
373    let remainder = chunks.remainder().len();
374    for chunk in chunks {
375        let a = u64::from_ne_bytes(chunk[0..8].try_into().unwrap());
376        let b = u64::from_ne_bytes(chunk[8..16].try_into().unwrap());
377        let c = u64::from_ne_bytes(chunk[16..24].try_into().unwrap());
378        let d = u64::from_ne_bytes(chunk[24..32].try_into().unwrap());
379        let e = u64::from_ne_bytes(chunk[32..40].try_into().unwrap());
380        let f = u64::from_ne_bytes(chunk[40..48].try_into().unwrap());
381        let g = u64::from_ne_bytes(chunk[48..56].try_into().unwrap());
382        let h = u64::from_ne_bytes(chunk[56..64].try_into().unwrap());
383        s0 = folded_multiply(a ^ s0, e ^ fold_seed);
384        s1 = folded_multiply(b ^ s1, f ^ fold_seed);
385        s2 = folded_multiply(c ^ s2, g ^ fold_seed);
386        s3 = folded_multiply(d ^ s3, h ^ fold_seed);
387    }
388    s0 ^= s2;
389    s1 ^= s3;
390
391    if remainder > 0 {
392        hash_bytes_medium(&bytes[bytes.len() - remainder.max(16)..], s0, s1, fold_seed)
393    } else {
394        s0 ^ s1
395    }
396}