hash-fast 0.1.0

Fast non-cryptographic hashing: the FxHash-family Hasher for maps and dedup tables, no_std, oracle-verified, avalanche-tested
Documentation
//! Fast non-cryptographic hashing: the estate's canonical map hash.
//!
//! FxHash-family multiply-xor accumulation over 8-byte chunks, with
//! two correctness features the family usually skips (both found by
//! this crate's own property suite, see git history):
//!
//! - **Streaming-correct**: values are buffered through an 8-byte tail
//!   and flushed on chunk boundaries, so `write(a); write(b)` produces
//!   exactly the same state as one `write(a ++ b)` - for every split.
//!   Hashing a struct's fields piecewise (the `Hasher` contract) is
//!   therefore equivalent to hashing the serialized whole.
//! - **Finalized**: `finish` applies a splitmix-style mix so the
//!   avalanche ratio lands near 50% (the raw recurrence measured
//!   0.387 - below the kit's [0.40, 0.60] window).
//!
//! Two surfaces:
//! - [`FastHasher`]: a [`core::hash::Hasher`] implementation, drop-in
//!   for `HashMap<K, V, FastHashBuilder>`.
//! - [`hash64`]: the one-shot byte-slice hash, for non-`Hash` inputs
//!   and for cross-referencing stored hashes. Stable across versions
//!   and processes (documented contract; `FastHasher`'s raw state is
//!   NOT stability-claimed).
//!
//! Non-cryptographic by design: no collision-resistance claims;
//! security-adjacent uses belong to the keyed-crypto domain.
//!
//! Hot path contract: no panics, no allocation, no syscalls, `no_std`.

#![no_std]

extern crate alloc;

use core::hash::Hasher;

/// The forever-oracle: an independent byte-assembly formulation of
/// the hash, differential-tested against the optimized forms. Never
/// optimized, never deleted (kit AGENTS.md).
pub mod oracle;

/// The `FxHash` 64-bit multiplier: `(2^64 + 2^5) / 5`, chosen so the low
/// bits spread through the multiply; the standard family constant.
const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;

/// The splitmix64 finalizer constants: one multiply-xor-shift round
/// takes the accumulator's avalanche ratio from 0.39 to ~0.50.
const FINALIZE_A: u64 = 0xFF51_AFD7_ED55_8CCD;
const FINALIZE_B: u64 = 0xC4CE_B9FE_1A85_EC53;

/// The FxHash-family hasher: a [`core::hash::Hasher`] for
/// `HashMap<K, V, FastHashBuilder>` and direct byte hashing.
///
/// Streaming-correct (see above): `write` calls may split anywhere.
/// Not cryptographically stable in its raw state; the one-shot
/// [`hash64`] documents its stability instead.
#[derive(Debug, Clone, Copy)]
pub struct FastHasher {
    state: u64,
    tail: [u8; 8],
    tail_len: usize,
}

impl FastHasher {
    /// New hasher with the zero state.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            state: 0,
            tail: [0; 8],
            tail_len: 0,
        }
    }

    /// The raw accumulator (diagnostic; `finish` is the hash).
    #[must_use]
    pub const fn state(&self) -> u64 {
        self.state
    }

    /// Feed raw bytes. Chunk-flush semantics: bytes accumulate through
    /// the tail buffer and each full 8-byte group folds immediately,
    /// so the state evolution is a pure function of the concatenated
    /// stream, not of the write-call boundaries.
    // indexing_slicing: tail_len < 8 is the flush invariant (reset to
    // 0 the moment it reaches 8), and 8 == tail.len()
    #[allow(clippy::indexing_slicing)]
    pub fn write_bytes(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.tail[self.tail_len] = b;
            self.tail_len += 1;
            if self.tail_len == 8 {
                let chunk = u64::from_le_bytes(self.tail);
                self.state = (self.state.rotate_left(5) ^ chunk).wrapping_mul(SEED);
                self.tail_len = 0;
            }
        }
    }

    /// Fold the buffered tail bytes, then finalize.
    fn finalized(&self) -> u64 {
        let mut s = self.state;
        for &b in self.tail.iter().take(self.tail_len) {
            s = (s.rotate_left(5) ^ u64::from(b)).wrapping_mul(SEED);
        }
        s ^= s >> 33;
        s = s.wrapping_mul(FINALIZE_A);
        s ^= s >> 33;
        s = s.wrapping_mul(FINALIZE_B);
        s ^= s >> 33;
        s
    }
}

impl Hasher for FastHasher {
    fn finish(&self) -> u64 {
        self.finalized()
    }

    fn write(&mut self, bytes: &[u8]) {
        self.write_bytes(bytes);
    }
}

/// The standalone byte-slice hash: one-shot, **stable across versions
/// and processes**. This is the contract that differs from
/// [`FastHasher`]'s raw state, whose finalization constants may change
/// on a version bump (map ordering is not a persisted contract).
///
/// Identical to `FastHasher::write_bytes` + `finish` (property-tested).
#[must_use]
pub fn hash64(bytes: &[u8]) -> u64 {
    let mut h = FastHasher::new();
    h.write_bytes(bytes);
    h.finish()
}

/// The builder for `HashMap<K, V, FastHashBuilder>` (the
/// `BuildHasher` contract).
#[derive(Debug, Clone, Copy, Default)]
pub struct FastHashBuilder;

impl Default for FastHasher {
    fn default() -> Self {
        Self::new()
    }
}

impl core::hash::BuildHasher for FastHashBuilder {
    type Hasher = FastHasher;

    fn build_hasher(&self) -> Self::Hasher {
        FastHasher::new()
    }
}