foldhash_portable/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_portable:
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_portable::{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_portable::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_portable, 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_portable::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_portable::quality::RandomState;
80//!
81//! let random_state = RandomState::default();
82//! let hash = random_state.hash_one("hello world");
83//! ```
84//!
85//! ## Seeding
86//!
87//! Foldhash relies on a single 8-byte per-hasher seed which should be ideally
88//! be different from each instance to instance, and also a larger
89//! [`SharedSeed`] which may be shared by many different instances.
90//!
91//! To reduce overhead, this [`SharedSeed`] is typically initialized once and
92//! stored. To prevent each hashmap unnecessarily containing a reference to this
93//! value there are three kinds of [`BuildHasher`](core::hash::BuildHasher)s
94//! foldhash provides (both for [`fast`] and [`quality`]):
95//!
96//! 1. [`RandomState`](fast::RandomState), which always generates a
97//! random per-hasher seed and implicitly stores a reference to [`SharedSeed::global_random`].
98//! 2. [`FixedState`](fast::FixedState), which by default uses a fixed
99//! per-hasher seed and implicitly stores a reference to [`SharedSeed::global_fixed`].
100//! 3. [`SeedableRandomState`](fast::SeedableRandomState), which works like
101//! [`RandomState`](fast::RandomState) by default but can be seeded in any manner.
102//! This state must include an explicit reference to a [`SharedSeed`], and thus
103//! this struct is 16 bytes as opposed to just 8 bytes for the previous two.
104//!
105//! ## Features
106//!
107//! This crate has the following features:
108//! - `nightly`, this feature improves string hashing performance
109//! slightly using the nightly-only Rust feature
110//! [`hasher_prefixfree_extras`](https://github.com/rust-lang/rust/issues/96762),
111//! - `std`, this enabled-by-default feature offers convenient aliases for `std`
112//! containers, but can be turned off for `#![no_std]` crates.
113//! - `portable`, this feature ensures hash output is identical across all
114//! platforms (endianness, 32-bit vs 64-bit) for the same input. This comes
115//! at a slight performance cost on big-endian and 32-bit platforms. Note that
116//! `write_usize` hashes are still inherently platform-dependent since `usize`
117//! has different widths on different platforms.
118
119#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
120#![cfg_attr(feature = "nightly", feature(hasher_prefixfree_extras))]
121#![warn(missing_docs)]
122
123pub mod fast;
124pub mod quality;
125mod seed;
126pub use seed::SharedSeed;
127
128#[cfg(feature = "std")]
129mod convenience;
130#[cfg(feature = "std")]
131pub use convenience::*;
132
133// Arbitrary constants with high entropy. Hexadecimal digits of pi were used.
134const ARBITRARY0: u64 = 0x243f6a8885a308d3;
135const ARBITRARY1: u64 = 0x13198a2e03707344;
136const ARBITRARY2: u64 = 0xa4093822299f31d0;
137const ARBITRARY3: u64 = 0x082efa98ec4e6c89;
138const ARBITRARY4: u64 = 0x452821e638d01377;
139const ARBITRARY5: u64 = 0xbe5466cf34e90c6c;
140const ARBITRARY6: u64 = 0xc0ac29b7c97c50dd;
141const ARBITRARY7: u64 = 0x3f84d5b5b5470917;
142const ARBITRARY8: u64 = 0x9216d5d98979fb1b;
143const ARBITRARY9: u64 = 0xd1310ba698dfb5ac;
144const ARBITRARY10: u64 = 0x2ffd72dbd01adfb7;
145const ARBITRARY11: u64 = 0xb8e1afed6a267e96;
146
147#[inline(always)]
148const fn folded_multiply(x: u64, y: u64) -> u64 {
149 // The following code path is only fast if 64-bit to 128-bit widening
150 // multiplication is supported by the architecture. Most 64-bit
151 // architectures except SPARC64 and Wasm64 support it. However, the target
152 // pointer width doesn't always indicate that we are dealing with a 64-bit
153 // architecture, as there are ABIs that reduce the pointer width, especially
154 // on AArch64 and x86-64. WebAssembly (regardless of pointer width) supports
155 // 64-bit to 128-bit widening multiplication with the `wide-arithmetic`
156 // proposal.
157 #[cfg(any(
158 feature = "portable",
159 all(
160 target_pointer_width = "64",
161 not(any(target_arch = "sparc64", target_arch = "wasm64")),
162 ),
163 target_arch = "aarch64",
164 target_arch = "x86_64",
165 all(target_family = "wasm", target_feature = "wide-arithmetic"),
166 ))]
167 {
168 // We compute the full u64 x u64 -> u128 product, this is a single mul
169 // instruction on x86-64, one mul plus one mulhi on ARM64.
170 let full = (x as u128).wrapping_mul(y as u128);
171 let lo = full as u64;
172 let hi = (full >> 64) as u64;
173
174 // The middle bits of the full product fluctuate the most with small
175 // changes in the input. This is the top bits of lo and the bottom bits
176 // of hi. We can thus make the entire output fluctuate with small
177 // changes to the input by XOR'ing these two halves.
178 lo ^ hi
179 }
180
181 #[cfg(not(any(
182 feature = "portable",
183 all(
184 target_pointer_width = "64",
185 not(any(target_arch = "sparc64", target_arch = "wasm64")),
186 ),
187 target_arch = "aarch64",
188 target_arch = "x86_64",
189 all(target_family = "wasm", target_feature = "wide-arithmetic"),
190 )))]
191 {
192 // u64 x u64 -> u128 product is quite expensive on 32-bit.
193 // We approximate it by expanding the multiplication and eliminating
194 // carries by replacing additions with XORs:
195 // (2^32 hx + lx)*(2^32 hy + ly) =
196 // 2^64 hx*hy + 2^32 (hx*ly + lx*hy) + lx*ly ~=
197 // 2^64 hx*hy ^ 2^32 (hx*ly ^ lx*hy) ^ lx*ly
198 // Which when folded becomes:
199 // (hx*hy ^ lx*ly) ^ (hx*ly ^ lx*hy).rotate_right(32)
200
201 let lx = x as u32;
202 let ly = y as u32;
203 let hx = (x >> 32) as u32;
204 let hy = (y >> 32) as u32;
205
206 let ll = (lx as u64).wrapping_mul(ly as u64);
207 let lh = (lx as u64).wrapping_mul(hy as u64);
208 let hl = (hx as u64).wrapping_mul(ly as u64);
209 let hh = (hx as u64).wrapping_mul(hy as u64);
210
211 (hh ^ ll) ^ (hl ^ lh).rotate_right(32)
212 }
213}
214
215#[inline(always)]
216const fn rotate_right(x: u64, r: u32) -> u64 {
217 #[cfg(any(
218 feature = "portable",
219 target_pointer_width = "64",
220 target_arch = "aarch64",
221 target_arch = "x86_64",
222 target_family = "wasm",
223 ))]
224 {
225 x.rotate_right(r)
226 }
227
228 #[cfg(not(any(
229 feature = "portable",
230 target_pointer_width = "64",
231 target_arch = "aarch64",
232 target_arch = "x86_64",
233 target_family = "wasm",
234 )))]
235 {
236 // On platforms without 64-bit arithmetic rotation can be slow, rotate
237 // each 32-bit half independently.
238 let lo = (x as u32).rotate_right(r);
239 let hi = ((x >> 32) as u32).rotate_right(r);
240 ((hi as u64) << 32) | lo as u64
241 }
242}
243
244#[cold]
245fn cold_path() {}
246
247#[inline(always)]
248fn read_u32(bytes: &[u8; 4]) -> u32 {
249 #[cfg(feature = "portable")]
250 { u32::from_le_bytes(*bytes) }
251 #[cfg(not(feature = "portable"))]
252 { u32::from_ne_bytes(*bytes) }
253}
254
255#[inline(always)]
256fn read_u64(bytes: &[u8; 8]) -> u64 {
257 #[cfg(feature = "portable")]
258 { u64::from_le_bytes(*bytes) }
259 #[cfg(not(feature = "portable"))]
260 { u64::from_ne_bytes(*bytes) }
261}
262
263/// Hashes strings <= 16 bytes, has unspecified behavior when bytes.len() > 16.
264#[inline(always)]
265fn hash_bytes_short(bytes: &[u8], accumulator: u64, seeds: &[u64; 6]) -> u64 {
266 let len = bytes.len();
267 let mut s0 = accumulator;
268 let mut s1 = seeds[1];
269 // XOR the input into s0, s1, then multiply and fold.
270 if len >= 8 {
271 s0 ^= read_u64(bytes[0..8].try_into().unwrap());
272 s1 ^= read_u64(bytes[len - 8..len].try_into().unwrap());
273 } else if len >= 4 {
274 s0 ^= read_u32(bytes[0..4].try_into().unwrap()) as u64;
275 s1 ^= read_u32(bytes[len - 4..len].try_into().unwrap()) as u64;
276 } else if len > 0 {
277 let lo = bytes[0];
278 let mid = bytes[len / 2];
279 let hi = bytes[len - 1];
280 s0 ^= lo as u64;
281 s1 ^= ((hi as u64) << 8) | mid as u64;
282 }
283 folded_multiply(s0, s1)
284}
285
286/// Load 8 bytes into a u64 word at the given offset.
287///
288/// # Safety
289/// You must ensure that offset + 8 <= bytes.len().
290#[inline(always)]
291unsafe fn load(bytes: &[u8], offset: usize) -> u64 {
292 // In most (but not all) cases this unsafe code is not necessary to avoid
293 // the bounds checks in the below code, but the register allocation became
294 // worse if I replaced those calls which could be replaced with safe code.
295 let val = unsafe { bytes.as_ptr().add(offset).cast::<u64>().read_unaligned() };
296 #[cfg(feature = "portable")]
297 { val.to_le() }
298 #[cfg(not(feature = "portable"))]
299 { val }
300}
301
302/// Hashes strings > 16 bytes.
303///
304/// # Safety
305/// v.len() must be > 16 bytes.
306#[cold]
307#[inline(never)]
308unsafe fn hash_bytes_long(mut v: &[u8], accumulator: u64, seeds: &[u64; 6]) -> u64 {
309 let mut s0 = accumulator;
310 let mut s1 = s0.wrapping_add(seeds[1]);
311
312 if v.len() > 128 {
313 cold_path();
314 let mut s2 = s0.wrapping_add(seeds[2]);
315 let mut s3 = s0.wrapping_add(seeds[3]);
316
317 if v.len() > 256 {
318 cold_path();
319 let mut s4 = s0.wrapping_add(seeds[4]);
320 let mut s5 = s0.wrapping_add(seeds[5]);
321 loop {
322 unsafe {
323 // SAFETY: we checked the length is > 256, we index at most v[..96].
324 s0 = folded_multiply(load(v, 0) ^ s0, load(v, 48) ^ seeds[0]);
325 s1 = folded_multiply(load(v, 8) ^ s1, load(v, 56) ^ seeds[0]);
326 s2 = folded_multiply(load(v, 16) ^ s2, load(v, 64) ^ seeds[0]);
327 s3 = folded_multiply(load(v, 24) ^ s3, load(v, 72) ^ seeds[0]);
328 s4 = folded_multiply(load(v, 32) ^ s4, load(v, 80) ^ seeds[0]);
329 s5 = folded_multiply(load(v, 40) ^ s5, load(v, 88) ^ seeds[0]);
330 }
331 v = &v[96..];
332 if v.len() <= 256 {
333 break;
334 }
335 }
336 s0 ^= s4;
337 s1 ^= s5;
338 }
339
340 loop {
341 unsafe {
342 // SAFETY: we checked the length is > 128, we index at most v[..64].
343 s0 = folded_multiply(load(v, 0) ^ s0, load(v, 32) ^ seeds[0]);
344 s1 = folded_multiply(load(v, 8) ^ s1, load(v, 40) ^ seeds[0]);
345 s2 = folded_multiply(load(v, 16) ^ s2, load(v, 48) ^ seeds[0]);
346 s3 = folded_multiply(load(v, 24) ^ s3, load(v, 56) ^ seeds[0]);
347 }
348 v = &v[64..];
349 if v.len() <= 128 {
350 break;
351 }
352 }
353 s0 ^= s2;
354 s1 ^= s3;
355 }
356
357 let len = v.len();
358 unsafe {
359 // SAFETY: our precondition ensures our length is at least 16, and the
360 // above loops do not reduce the length under that. This protects our
361 // first iteration of this loop, the further iterations are protected
362 // directly by the checks on len.
363 s0 = folded_multiply(load(v, 0) ^ s0, load(v, len - 16) ^ seeds[0]);
364 s1 = folded_multiply(load(v, 8) ^ s1, load(v, len - 8) ^ seeds[0]);
365 if len >= 32 {
366 s0 = folded_multiply(load(v, 16) ^ s0, load(v, len - 32) ^ seeds[0]);
367 s1 = folded_multiply(load(v, 24) ^ s1, load(v, len - 24) ^ seeds[0]);
368 if len >= 64 {
369 s0 = folded_multiply(load(v, 32) ^ s0, load(v, len - 48) ^ seeds[0]);
370 s1 = folded_multiply(load(v, 40) ^ s1, load(v, len - 40) ^ seeds[0]);
371 if len >= 96 {
372 s0 = folded_multiply(load(v, 48) ^ s0, load(v, len - 64) ^ seeds[0]);
373 s1 = folded_multiply(load(v, 56) ^ s1, load(v, len - 56) ^ seeds[0]);
374 }
375 }
376 }
377 }
378 s0 ^ s1
379}