# `ihb2032/tervyx/hash` — 64-Bit Non-Cryptographic Hashing (XXH64 + RapidHash Streaming)

## 1. Purpose, Cross-Language Selection & Tradeoffs

MoonBit's standard library provides a 32-bit `Hasher` for general hash tables,
but content fingerprinting, shard routing, Bloom filters, and cross-language
checksums benefit from a 64-bit output space and wide-lane bulk throughput.
`ihb2032/tervyx/hash` provides a standalone 64-bit non-cryptographic hashing
package:

- **Cross-language design influences**:
  - **C / C++ (`xxHash` XXH64)**: 4 independent 64-bit accumulators (32 bytes per stripe for high instruction-level parallelism) paired with zero-copy little-endian `u64le` bitstring loads.
  - **C++ / Rust (`rapidhash` / `wyhash` / `SplitMix64`)**: 128-bit folded multiply mixer `@hash.fold_mul` (XOR of high and low 64-bit halves with zero heap allocation) and `@hash.mix64` finalizer for strong avalanche on short keys and streaming inputs.
  - **Rust (`std::hash::Hasher`)**: Stateful streaming `@hash.RapidHasher` (`write_byte`, `write_bytes`, `write_int`, `write_int64`, `write_uint64`, `write_string`, `finish`) alongside one-shot functions `@hash.hash_bytes`, `@hash.hash_string`, `@hash.hash_int`, `@hash.hash_int64`, and `@hash.hash_uint64` with optional `seed~`.
- **Rejected alternatives**:
  - **SipHash**: Cryptographic HashDoS resistance adds substantial per-block round overhead unnecessary for non-adversarial throughput workloads.
  - **128-bit-multiply bulk main loop**: Emulating `u64 × u64 -> u128` inside a tight bulk loop is slower on Wasm32 and JS than XXH64's 64-bit multiply-rotate lanes.

## 2. MoonBit Data Layout & Multi-Backend Tradeoffs

- **Per-target compilation split**:
  - `wasm`, `wasm-gc`, `native` (`hash/rapid_u64.mbt`): native 64-bit `UInt64` four-stripe XXH64 with direct-offset `Bytes::unsafe_read_uint64_le` / `Bytes::unsafe_read_uint32_le` / `Bytes::unsafe_get` after unpacking `BytesView::data()` and `start_offset()` once. `@hash.hash_string` similarly unpacks `StringView::data()` and `start_offset()` once and packs 4 UTF-16 code units per 64-bit lane without UTF-8 transcoding.
  - `js` (`hash/rapid_js.mbt`): on `js`, MoonBit lowers `UInt64` arithmetic to heap-allocated `BigInt` calls (`BigInt.asUintN`) and `unsafe_read_uint64_le` to `DataView` allocations. `hash/rapid_js.mbt` implements bit-exact XXH64 (`hash_bytes` and `hash_string`) using signed 32-bit `Int32` `(lo, hi)` halves (`Math.imul` + `| 0` additions with zero `BigInt`/`DataView` allocations inside the loops), speeding up JS hashing by **2.62×–4.42×** while producing identical 64-bit digests across the 4 targets.
- **32-bit vs 64-bit hashing guidance on `js`**: Even with unboxed 32-bit `(lo, hi)` emulation, 64-bit XXH64 performs ~12 `Math.imul` operations per 8 bytes versus 1 `Math.imul` per 4 bytes for 32-bit `core` hashing. When targeting `js` for internal hash-table indexing without 64-bit fingerprint requirements, prefer 32-bit hashing (for example, `flat_map` uses pure 32-bit `fmix32`).

## 3. Invariants & Verification

- **Cross-backend bit determinism**: Identical inputs and seeds produce bit-exact `UInt64` outputs across `wasm`, `wasm-gc`, `js`, and `native`, validated against official XXH64 reference vectors plus 12 pinned cross-backend stress vectors (lengths 32–160, non-zero slice offsets, `0xFFFFFFFFFFFFFFFFUL` carry-edge seeds, and multi-byte UTF-16 strings).
- **Length-delimited streaming**: `RapidHasher` mixes chunk lengths to prevent prefix-concatenation ambiguity between `("ab", "c")` and `("a", "bc")`.
- **Test matrix**: Covers 1-bit flip avalanche distribution, seed independence, boundary lengths `0..=160`, and 100% line coverage.

## 4. 4-Backend `--release` Benchmarks (WSL2 Local)

Environment: **AMD Ryzen 7 7840HS** (16 CPUs), `Linux 6.18.58.1-microsoft-standard-WSL2`,
MoonBit `v1.0.0-rc1+3c0520448`, `moon bench -p ihb2032/tervyx/hash --target all --release`.

| Benchmark | `wasm` | `wasm-gc` | `js` | `native` |
| :--- | ---: | ---: | ---: | ---: |
| `bench_hash_bytes_64_tervyx` | `35.79 ns` | `36.02 ns` | `228.98 ns` | `15.09 ns` |
| `bench_hash_bytes_64_core` | `37.75 ns` | `33.28 ns` | `39.75 ns` | `17.91 ns` |
| `bench_hash_bytes_4096_tervyx` | `255.85 ns` | `1.40 µs` | `4.41 µs` | `312.57 ns` |
| `bench_hash_bytes_4096_core` | `1.35 µs` | `1.65 µs` | `2.07 µs` | `1.31 µs` |
| `bench_hash_string_64_tervyx` | `48.98 ns` | `35.42 ns` | `259.99 ns` | `29.65 ns` |
| `bench_hash_string_64_core` | `90.78 ns` | `84.14 ns` | `82.22 ns` | `78.17 ns` |

### Takeaways & Guidance

- **4096 B buffers**: Direct-offset `unsafe_read_uint64_le` achieves **`255.85 ns`** on `wasm` (~`16.0 GB/s`, **5.28×** faster than `core` 32-bit `Hasher`), **`312.57 ns`** on `native` (~`13.1 GB/s`, **4.19×** faster), and **`1.40 µs`** on `wasm-gc` (**1.18×** faster while producing 64-bit hashes).
- **64-char strings**: **2.64×** faster on `native`, **2.38×** on `wasm-gc`, and **1.85×** on `wasm`.
- **JS target**: The zero-`BigInt` 32-bit `(lo, hi)` backend cuts `hash_bytes(4096 B)` from `19.13 µs` to **`4.41 µs`** (**4.34×** faster), `hash_bytes(64 B)` from `599.67 ns` to **`228.98 ns`** (**2.62×** faster), and `hash_string(64)` from `1.15 µs` to **`259.99 ns`** (**4.42×** faster) while maintaining bit-exact cross-backend XXH64 parity.
