Skip to main content

hash_fast/
lib.rs

1//! Fast non-cryptographic hashing: the estate's canonical map hash.
2//!
3//! FxHash-family multiply-xor accumulation over 8-byte chunks, with
4//! two correctness features the family usually skips (both found by
5//! this crate's own property suite, see git history):
6//!
7//! - **Streaming-correct**: values are buffered through an 8-byte tail
8//!   and flushed on chunk boundaries, so `write(a); write(b)` produces
9//!   exactly the same state as one `write(a ++ b)` - for every split.
10//!   Hashing a struct's fields piecewise (the `Hasher` contract) is
11//!   therefore equivalent to hashing the serialized whole.
12//! - **Finalized**: `finish` applies a splitmix-style mix so the
13//!   avalanche ratio lands near 50% (the raw recurrence measured
14//!   0.387 - below the kit's [0.40, 0.60] window).
15//!
16//! Two surfaces:
17//! - [`FastHasher`]: a [`core::hash::Hasher`] implementation, drop-in
18//!   for `HashMap<K, V, FastHashBuilder>`.
19//! - [`hash64`]: the one-shot byte-slice hash, for non-`Hash` inputs
20//!   and for cross-referencing stored hashes. Stable across versions
21//!   and processes (documented contract; `FastHasher`'s raw state is
22//!   NOT stability-claimed).
23//!
24//! Non-cryptographic by design: no collision-resistance claims;
25//! security-adjacent uses belong to the keyed-crypto domain.
26//!
27//! Hot path contract: no panics, no allocation, no syscalls, `no_std`.
28
29#![no_std]
30
31extern crate alloc;
32
33use core::hash::Hasher;
34
35/// The forever-oracle: an independent byte-assembly formulation of
36/// the hash, differential-tested against the optimized forms. Never
37/// optimized, never deleted (kit AGENTS.md).
38pub mod oracle;
39
40/// The `FxHash` 64-bit multiplier: `(2^64 + 2^5) / 5`, chosen so the low
41/// bits spread through the multiply; the standard family constant.
42const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
43
44/// The splitmix64 finalizer constants: one multiply-xor-shift round
45/// takes the accumulator's avalanche ratio from 0.39 to ~0.50.
46const FINALIZE_A: u64 = 0xFF51_AFD7_ED55_8CCD;
47const FINALIZE_B: u64 = 0xC4CE_B9FE_1A85_EC53;
48
49/// The FxHash-family hasher: a [`core::hash::Hasher`] for
50/// `HashMap<K, V, FastHashBuilder>` and direct byte hashing.
51///
52/// Streaming-correct (see above): `write` calls may split anywhere.
53/// Not cryptographically stable in its raw state; the one-shot
54/// [`hash64`] documents its stability instead.
55#[derive(Debug, Clone, Copy)]
56pub struct FastHasher {
57    state: u64,
58    tail: [u8; 8],
59    tail_len: usize,
60}
61
62impl FastHasher {
63    /// New hasher with the zero state.
64    #[must_use]
65    pub const fn new() -> Self {
66        Self {
67            state: 0,
68            tail: [0; 8],
69            tail_len: 0,
70        }
71    }
72
73    /// The raw accumulator (diagnostic; `finish` is the hash).
74    #[must_use]
75    pub const fn state(&self) -> u64 {
76        self.state
77    }
78
79    /// Feed raw bytes. Chunk-flush semantics: bytes accumulate through
80    /// the tail buffer and each full 8-byte group folds immediately,
81    /// so the state evolution is a pure function of the concatenated
82    /// stream, not of the write-call boundaries.
83    // indexing_slicing: tail_len < 8 is the flush invariant (reset to
84    // 0 the moment it reaches 8), and 8 == tail.len()
85    #[allow(clippy::indexing_slicing)]
86    pub fn write_bytes(&mut self, bytes: &[u8]) {
87        for &b in bytes {
88            self.tail[self.tail_len] = b;
89            self.tail_len += 1;
90            if self.tail_len == 8 {
91                let chunk = u64::from_le_bytes(self.tail);
92                self.state = (self.state.rotate_left(5) ^ chunk).wrapping_mul(SEED);
93                self.tail_len = 0;
94            }
95        }
96    }
97
98    /// Fold the buffered tail bytes, then finalize.
99    fn finalized(&self) -> u64 {
100        let mut s = self.state;
101        for &b in self.tail.iter().take(self.tail_len) {
102            s = (s.rotate_left(5) ^ u64::from(b)).wrapping_mul(SEED);
103        }
104        s ^= s >> 33;
105        s = s.wrapping_mul(FINALIZE_A);
106        s ^= s >> 33;
107        s = s.wrapping_mul(FINALIZE_B);
108        s ^= s >> 33;
109        s
110    }
111}
112
113impl Hasher for FastHasher {
114    fn finish(&self) -> u64 {
115        self.finalized()
116    }
117
118    fn write(&mut self, bytes: &[u8]) {
119        self.write_bytes(bytes);
120    }
121}
122
123/// The standalone byte-slice hash: one-shot, **stable across versions
124/// and processes**. This is the contract that differs from
125/// [`FastHasher`]'s raw state, whose finalization constants may change
126/// on a version bump (map ordering is not a persisted contract).
127///
128/// Identical to `FastHasher::write_bytes` + `finish` (property-tested).
129#[must_use]
130pub fn hash64(bytes: &[u8]) -> u64 {
131    let mut h = FastHasher::new();
132    h.write_bytes(bytes);
133    h.finish()
134}
135
136/// The builder for `HashMap<K, V, FastHashBuilder>` (the
137/// `BuildHasher` contract).
138#[derive(Debug, Clone, Copy, Default)]
139pub struct FastHashBuilder;
140
141impl Default for FastHasher {
142    fn default() -> Self {
143        Self::new()
144    }
145}
146
147impl core::hash::BuildHasher for FastHashBuilder {
148    type Hasher = FastHasher;
149
150    fn build_hasher(&self) -> Self::Hasher {
151        FastHasher::new()
152    }
153}