ctb_formats_checksum/
fnv.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Fowler-Noll-Vo (FNV-0, FNV-1, FNV-1a) hash functions computed from scratch.
21//!
22//! FIXME: They can be folded to arbitrary bit lengths (`fnv_xor_fold`) but
23//! there's no `FormatId` or parameterized format variant for that.
24//!
25//! Provides an independent implementation of 32, 64, 128, 256, 512, and
26//! 1024-bit FNV hashes derived from the mathematical specifications of
27//! RFC 9923 ("The FNV Non-Cryptographic Hash Algorithm", February 2026),
28//! without using reference source code:
29//! - Section 1.4 & Section 6: Non-cryptographic characteristics (sticky state,
30//!   dispersion limits on low bits, low work factor) and security
31//!   considerations regarding collision resistance.
32//! - Section 2 & Section 5: Core FNV-0, FNV-1, and FNV-1a algorithms, primes,
33//!   and offset bases.
34//! - Section 2.3: Little-endian representation for storage and interoperability.
35//! - Section 3: XOR folding to arbitrary bit widths and modulo range mapping
36//!   with retry-based bias avoidance.
37//! - Section 4: Hashing multiple values together and support for non-standard
38//!   `offset_basis` values.
39//!
40//! All offset bases are derived dynamically by executing the n-bit FNV-0
41//! algorithm over the standard 32-octet basis string (`FNV_BASIS_STRING`).
42//! FNV primes are constructed according to the formula:
43//! `FNV_Prime = 256**k + 2**8 + b` where `k = int((5 + 2**s) / 12)`.
44
45#[allow(
46    unused_imports,
47    clippy::wildcard_imports,
48    reason = "Standard workspace crate prelude"
49)]
50pub(crate) use ctb_utilities::*;
51
52use ctb_formats_math::Natural;
53use ctb_utilities::string::to_hex;
54
55/// Standard FNV offset basis derivation string from RFC 9923 Section 2.2.
56///
57/// In C string literal notation: `"chongo <Landon Curt Noll> /\\../\\"`.
58pub const FNV_BASIS_STRING: &[u8; 32] = b"chongo <Landon Curt Noll> /\\../\\";
59
60/// Represents an algorithm variant of the Fowler-Noll-Vo hash family.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum FnvVariant {
63    /// FNV-0 (offset basis 0; multiply then XOR).
64    Fnv0,
65    /// FNV-1 (signature offset basis; multiply then XOR).
66    Fnv1,
67    /// FNV-1a (signature offset basis; XOR then multiply).
68    Fnv1a,
69}
70
71/// A fixed-width unsigned word for FNV calculations, stored in little-endian
72/// byte order (`bytes[0]` is least significant).
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct FnvWord<const BYTES: usize> {
75    /// Little-endian bytes representation of the integer value.
76    pub bytes: [u8; BYTES],
77}
78
79impl<const BYTES: usize> Default for FnvWord<BYTES> {
80    fn default() -> Self {
81        Self::zero()
82    }
83}
84
85impl<const BYTES: usize> FnvWord<BYTES> {
86    /// Creates a zero-initialized word.
87    #[must_use]
88    pub const fn zero() -> Self {
89        Self {
90            bytes: [0_u8; BYTES],
91        }
92    }
93
94    /// Creates a word initialized from a little-endian byte array.
95    #[must_use]
96    pub const fn from_le_bytes(bytes: [u8; BYTES]) -> Self {
97        Self { bytes }
98    }
99
100    /// Creates a word initialized from a big-endian byte array.
101    #[must_use]
102    pub fn from_be_bytes(mut bytes: [u8; BYTES]) -> Self {
103        bytes.reverse();
104        Self { bytes }
105    }
106
107    /// Returns the big-endian representation of the word (most significant
108    /// byte first), suitable for standard hex string formatting.
109    #[must_use]
110    pub fn to_be_bytes(self) -> [u8; BYTES] {
111        let mut out = self.bytes;
112        out.reverse();
113        out
114    }
115
116    /// Returns the little-endian representation of the word (least
117    /// significant byte first), per RFC 9923 Section 2.3 for storage.
118    #[must_use]
119    pub const fn to_le_bytes(self) -> [u8; BYTES] {
120        self.bytes
121    }
122
123    /// Converts the word to a lowercase hex string (in big-endian order).
124    #[must_use]
125    pub fn to_hex(self) -> String {
126        to_hex(&self.to_be_bytes())
127    }
128
129    /// Multiplies `self` modulo $2^{\text{BYTES} \times 8}$ by an FNV prime of
130    /// the form $256^k + 2^8 + b$.
131    ///
132    /// The multiplication is expanded as:
133    /// `(self << (k * 8)) + (self << 8) + (self * b)`
134    /// where `k` and `1` are exact byte shifts, and `b` is a 1-byte scalar.
135    pub fn multiply_fnv_prime(&mut self, k: usize, b: u8) {
136        let mut term1 = [0_u8; BYTES];
137        let mut term2 = [0_u8; BYTES];
138        let mut term3 = [0_u8; BYTES];
139
140        // term1 = self << (k * 8)
141        for (i, byte) in self.bytes.iter().enumerate() {
142            if let Some(target_idx) = i.checked_add(k) {
143                if let Some(slot) = term1.get_mut(target_idx) {
144                    *slot = *byte;
145                }
146            }
147        }
148
149        // term2 = self << 8
150        for (i, byte) in self.bytes.iter().enumerate() {
151            if let Some(target_idx) = i.checked_add(1) {
152                if let Some(slot) = term2.get_mut(target_idx) {
153                    *slot = *byte;
154                }
155            }
156        }
157
158        // term3 = self * b
159        let mut carry: u16 = 0;
160        for (i, byte) in self.bytes.iter().enumerate() {
161            let prod = u16::from(*byte)
162                .wrapping_mul(u16::from(b))
163                .wrapping_add(carry);
164            if let Some(slot) = term3.get_mut(i) {
165                if let Ok(b_val) = u8::try_from(prod & 0xff) {
166                    *slot = b_val;
167                }
168            }
169            carry = prod >> 8;
170        }
171
172        // Sum term1 + term2 + term3 modulo 2^(BYTES * 8)
173        let mut sum_carry: u16 = 0;
174        for (((slot, &b1), &b2), &b3) in self
175            .bytes
176            .iter_mut()
177            .zip(term1.iter())
178            .zip(term2.iter())
179            .zip(term3.iter())
180        {
181            let s = u16::from(b1)
182                .wrapping_add(u16::from(b2))
183                .wrapping_add(u16::from(b3))
184                .wrapping_add(sum_carry);
185            if let Ok(val) = u8::try_from(s & 0xff) {
186                *slot = val;
187            }
188            sum_carry = s >> 8;
189        }
190    }
191
192    /// XORs the lowest octet of the word with `octet`.
193    pub fn xor_octet(&mut self, octet: u8) {
194        if let Some(first) = self.bytes.get_mut(0) {
195            *first ^= octet;
196        }
197    }
198
199    /// Bitwise right shifts the word by `shift_bits` bits.
200    #[must_use]
201    pub fn shift_right_bits(self, shift_bits: usize) -> Self {
202        let byte_shift = shift_bits / 8;
203        let bit_shift = shift_bits % 8;
204        let mut out = [0_u8; BYTES];
205        for (i, slot) in out.iter_mut().enumerate() {
206            if let Some(src_idx) = i.checked_add(byte_shift) {
207                if let Some(low_byte) = self.bytes.get(src_idx) {
208                    let low_part = *low_byte >> bit_shift;
209                    let mut high_part = 0_u8;
210                    if bit_shift > 0 {
211                        if let Some(high_byte) =
212                            self.bytes.get(src_idx.saturating_add(1))
213                        {
214                            let shift_up = 8_usize.saturating_sub(bit_shift);
215                            if let Ok(shl_val) = u8::try_from(
216                                (u16::from(*high_byte) << shift_up) & 0xff,
217                            ) {
218                                high_part = shl_val;
219                            }
220                        }
221                    }
222                    *slot = low_part | high_part;
223                }
224            }
225        }
226        Self { bytes: out }
227    }
228
229    /// Performs bitwise XOR between two words.
230    #[must_use]
231    pub fn xor(mut self, other: Self) -> Self {
232        for (a, b) in self.bytes.iter_mut().zip(other.bytes.iter()) {
233            *a ^= *b;
234        }
235        self
236    }
237
238    /// Masks the word to only retain the lowest `k` bits.
239    #[must_use]
240    pub fn mask_bits(mut self, k: usize) -> Self {
241        for (i, byte) in self.bytes.iter_mut().enumerate() {
242            let bit_start = i.saturating_mul(8);
243            if bit_start >= k {
244                *byte = 0;
245            } else if bit_start.saturating_add(8) > k {
246                let rem = k.saturating_sub(bit_start);
247                let mask = (1_u16 << rem).wrapping_sub(1);
248                if let Ok(mask_byte) = u8::try_from(mask) {
249                    *byte &= mask_byte;
250                }
251            }
252        }
253        self
254    }
255
256    /// Returns the big-endian representation of the lowest `num_bytes` bytes.
257    #[must_use]
258    pub fn to_trimmed_be_bytes(self, num_bytes: usize) -> Vec<u8> {
259        let mut slice: Vec<u8> =
260            self.bytes.into_iter().take(num_bytes).collect();
261        slice.reverse();
262        slice
263    }
264}
265
266impl FnvWord<4> {
267    /// Converts a 4-byte word to a native `u32`.
268    #[must_use]
269    pub fn as_u32(self) -> u32 {
270        u32::from_le_bytes(self.bytes)
271    }
272
273    /// Converts a native `u32` to a 4-byte word.
274    #[must_use]
275    pub fn from_u32(val: u32) -> Self {
276        Self {
277            bytes: val.to_le_bytes(),
278        }
279    }
280}
281
282impl FnvWord<8> {
283    /// Converts an 8-byte word to a native `u64`.
284    #[must_use]
285    pub fn as_u64(self) -> u64 {
286        u64::from_le_bytes(self.bytes)
287    }
288
289    /// Converts a native `u64` to an 8-byte word.
290    #[must_use]
291    pub fn from_u64(val: u64) -> Self {
292        Self {
293            bytes: val.to_le_bytes(),
294        }
295    }
296}
297
298impl FnvWord<16> {
299    /// Converts a 16-byte word to a native `u128`.
300    #[must_use]
301    pub fn as_u128(self) -> u128 {
302        u128::from_le_bytes(self.bytes)
303    }
304
305    /// Converts a native `u128` to a 16-byte word.
306    #[must_use]
307    pub fn from_u128(val: u128) -> Self {
308        Self {
309            bytes: val.to_le_bytes(),
310        }
311    }
312}
313
314// ----------------------------------------------------------------------------
315// Core Algorithm Drivers
316// ----------------------------------------------------------------------------
317
318/// Updates an existing FNV-0 hash with data.
319#[must_use]
320pub fn fnv0_update_word<const BYTES: usize>(
321    mut hash: FnvWord<BYTES>,
322    k: usize,
323    b: u8,
324    data: &[u8],
325) -> FnvWord<BYTES> {
326    for octet in data {
327        hash.multiply_fnv_prime(k, b);
328        hash.xor_octet(*octet);
329    }
330    hash
331}
332
333/// Updates an existing FNV-1 hash with data.
334#[must_use]
335pub fn fnv1_update_word<const BYTES: usize>(
336    mut hash: FnvWord<BYTES>,
337    k: usize,
338    b: u8,
339    data: &[u8],
340) -> FnvWord<BYTES> {
341    for octet in data {
342        hash.multiply_fnv_prime(k, b);
343        hash.xor_octet(*octet);
344    }
345    hash
346}
347
348/// Updates an existing FNV-1a hash with data.
349#[must_use]
350pub fn fnv1a_update_word<const BYTES: usize>(
351    mut hash: FnvWord<BYTES>,
352    k: usize,
353    b: u8,
354    data: &[u8],
355) -> FnvWord<BYTES> {
356    for octet in data {
357        hash.xor_octet(*octet);
358        hash.multiply_fnv_prime(k, b);
359    }
360    hash
361}
362
363/// Computes the offset basis for an n-bit FNV hash by running FNV-0 over the
364/// 32-octet Landon Curt Noll signature string, per RFC 9923 Section 2.2.
365#[must_use]
366pub fn compute_offset_basis<const BYTES: usize>(
367    k: usize,
368    b: u8,
369) -> FnvWord<BYTES> {
370    fnv0_update_word(FnvWord::zero(), k, b, FNV_BASIS_STRING)
371}
372
373/// Streaming hasher for incremental FNV hash computation.
374#[derive(Debug, Clone)]
375pub struct FnvStream<const BYTES: usize> {
376    variant: FnvVariant,
377    k: usize,
378    b: u8,
379    state: FnvWord<BYTES>,
380}
381
382impl<const BYTES: usize> FnvStream<BYTES> {
383    /// Creates a new streaming hasher for the given variant and prime params.
384    #[must_use]
385    pub fn new(variant: FnvVariant, k: usize, b: u8) -> Self {
386        let initial_state = match variant {
387            FnvVariant::Fnv0 => FnvWord::zero(),
388            FnvVariant::Fnv1 | FnvVariant::Fnv1a => compute_offset_basis(k, b),
389        };
390        Self {
391            variant,
392            k,
393            b,
394            state: initial_state,
395        }
396    }
397
398    /// Creates a streaming hasher with a custom initial `offset_basis`,
399    /// per RFC 9923 Section 4 and Section 8.1.1.
400    #[must_use]
401    pub fn with_basis(
402        variant: FnvVariant,
403        k: usize,
404        b: u8,
405        offset_basis: FnvWord<BYTES>,
406    ) -> Self {
407        Self {
408            variant,
409            k,
410            b,
411            state: offset_basis,
412        }
413    }
414
415    /// Feeds additional bytes into the hasher.
416    pub fn update(&mut self, data: &[u8]) {
417        match self.variant {
418            FnvVariant::Fnv0 => {
419                self.state = fnv0_update_word(self.state, self.k, self.b, data);
420            }
421            FnvVariant::Fnv1 => {
422                self.state = fnv1_update_word(self.state, self.k, self.b, data);
423            }
424            FnvVariant::Fnv1a => {
425                self.state =
426                    fnv1a_update_word(self.state, self.k, self.b, data);
427            }
428        }
429    }
430
431    /// Finalizes the hash and returns the raw word.
432    #[must_use]
433    pub fn finalize(self) -> FnvWord<BYTES> {
434        self.state
435    }
436
437    /// Finalizes the hash and returns its big-endian lowercase hex string.
438    #[must_use]
439    pub fn finalize_hex(self) -> String {
440        self.state.to_hex()
441    }
442}
443
444impl<const BYTES: usize> std::io::Write for FnvStream<BYTES> {
445    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
446        self.update(buf);
447        Ok(buf.len())
448    }
449
450    fn flush(&mut self) -> std::io::Result<()> {
451        Ok(())
452    }
453}
454
455// ----------------------------------------------------------------------------
456// 32-bit FNV Implementations (s=5, k=3, b=0x93)
457// ----------------------------------------------------------------------------
458
459pub(crate) const K_32: usize = 3;
460pub(crate) const B_32: u8 = 0x93;
461
462/// Computes the 32-bit FNV-0 hash of `data`.
463#[must_use]
464pub fn fnv0_32(data: &[u8]) -> u32 {
465    fnv0_update_word(FnvWord::<4>::zero(), K_32, B_32, data).as_u32()
466}
467
468/// Computes the 32-bit FNV-0 hash of `data` as a lowercase hex string.
469#[must_use]
470pub fn fnv0_32_hex(data: impl AsRef<[u8]>) -> String {
471    to_hex(&fnv0_32(data.as_ref()).to_be_bytes())
472}
473
474/// Computes the 32-bit FNV-1 hash of `data`.
475#[must_use]
476pub fn fnv1_32(data: &[u8]) -> u32 {
477    let basis = compute_offset_basis::<4>(K_32, B_32);
478    fnv1_update_word(basis, K_32, B_32, data).as_u32()
479}
480
481/// Computes the 32-bit FNV-1 hash of `data` as a lowercase hex string.
482#[must_use]
483pub fn fnv1_32_hex(data: impl AsRef<[u8]>) -> String {
484    to_hex(&fnv1_32(data.as_ref()).to_be_bytes())
485}
486
487/// Updates an existing 32-bit FNV-1a hash with `data`.
488#[must_use]
489pub fn fnv1a_32_update(hash: u32, data: &[u8]) -> u32 {
490    fnv1a_update_word(FnvWord::from_u32(hash), K_32, B_32, data).as_u32()
491}
492
493/// Computes the 32-bit FNV-1a hash of `data`.
494#[must_use]
495pub fn fnv1a_32(data: &[u8]) -> u32 {
496    let basis = compute_offset_basis::<4>(K_32, B_32);
497    fnv1a_update_word(basis, K_32, B_32, data).as_u32()
498}
499
500/// Computes the 32-bit FNV-1a hash of `data` using a custom `offset_basis`,
501/// per RFC 9923 Section 4.
502#[must_use]
503pub fn fnv1a_32_with_basis(offset_basis: u32, data: &[u8]) -> u32 {
504    fnv1a_32_update(offset_basis, data)
505}
506
507/// Computes the 32-bit FNV-1a hash of `data` as a lowercase hex string.
508#[must_use]
509pub fn fnv1a_32_hex(data: impl AsRef<[u8]>) -> String {
510    to_hex(&fnv1a_32(data.as_ref()).to_be_bytes())
511}
512
513// ----------------------------------------------------------------------------
514// 64-bit FNV Implementations (s=6, k=5, b=0xb3)
515// ----------------------------------------------------------------------------
516
517pub(crate) const K_64: usize = 5;
518pub(crate) const B_64: u8 = 0xb3;
519
520/// Computes the 64-bit FNV-0 hash of `data`.
521#[must_use]
522pub fn fnv0_64(data: &[u8]) -> u64 {
523    fnv0_update_word(FnvWord::<8>::zero(), K_64, B_64, data).as_u64()
524}
525
526/// Computes the 64-bit FNV-0 hash of `data` as a lowercase hex string.
527#[must_use]
528pub fn fnv0_64_hex(data: impl AsRef<[u8]>) -> String {
529    to_hex(&fnv0_64(data.as_ref()).to_be_bytes())
530}
531
532/// Computes the 64-bit FNV-1 hash of `data`.
533#[must_use]
534pub fn fnv1_64(data: &[u8]) -> u64 {
535    let basis = compute_offset_basis::<8>(K_64, B_64);
536    fnv1_update_word(basis, K_64, B_64, data).as_u64()
537}
538
539/// Computes the 64-bit FNV-1 hash of `data` as a lowercase hex string.
540#[must_use]
541pub fn fnv1_64_hex(data: impl AsRef<[u8]>) -> String {
542    to_hex(&fnv1_64(data.as_ref()).to_be_bytes())
543}
544
545/// Updates an existing 64-bit FNV-1a hash with `data`.
546#[must_use]
547pub fn fnv1a_64_update(hash: u64, data: &[u8]) -> u64 {
548    fnv1a_update_word(FnvWord::from_u64(hash), K_64, B_64, data).as_u64()
549}
550
551/// Computes the 64-bit FNV-1a hash of `data`.
552#[must_use]
553pub fn fnv1a_64(data: &[u8]) -> u64 {
554    let basis = compute_offset_basis::<8>(K_64, B_64);
555    fnv1a_update_word(basis, K_64, B_64, data).as_u64()
556}
557
558/// Computes the 64-bit FNV-1a hash of `data` using a custom `offset_basis`,
559/// per RFC 9923 Section 4.
560#[must_use]
561pub fn fnv1a_64_with_basis(offset_basis: u64, data: &[u8]) -> u64 {
562    fnv1a_64_update(offset_basis, data)
563}
564
565/// Computes the 64-bit FNV-1a hash of `data` as a lowercase hex string.
566#[must_use]
567pub fn fnv1a_64_hex(data: impl AsRef<[u8]>) -> String {
568    to_hex(&fnv1a_64(data.as_ref()).to_be_bytes())
569}
570
571// ----------------------------------------------------------------------------
572// 128-bit FNV Implementations (s=7, k=11, b=0x3b)
573// ----------------------------------------------------------------------------
574
575pub(crate) const K_128: usize = 11;
576pub(crate) const B_128: u8 = 0x3b;
577
578/// Computes the 128-bit FNV-0 hash of `data`.
579#[must_use]
580pub fn fnv0_128(data: &[u8]) -> u128 {
581    fnv0_update_word(FnvWord::<16>::zero(), K_128, B_128, data).as_u128()
582}
583
584/// Computes the 128-bit FNV-0 hash of `data` as a lowercase hex string.
585#[must_use]
586pub fn fnv0_128_hex(data: impl AsRef<[u8]>) -> String {
587    to_hex(&fnv0_128(data.as_ref()).to_be_bytes())
588}
589
590/// Computes the 128-bit FNV-1 hash of `data`.
591#[must_use]
592pub fn fnv1_128(data: &[u8]) -> u128 {
593    let basis = compute_offset_basis::<16>(K_128, B_128);
594    fnv1_update_word(basis, K_128, B_128, data).as_u128()
595}
596
597/// Computes the 128-bit FNV-1 hash of `data` as a lowercase hex string.
598#[must_use]
599pub fn fnv1_128_hex(data: impl AsRef<[u8]>) -> String {
600    to_hex(&fnv1_128(data.as_ref()).to_be_bytes())
601}
602
603/// Updates an existing 128-bit FNV-1a hash with `data`.
604#[must_use]
605pub fn fnv1a_128_update(hash: u128, data: &[u8]) -> u128 {
606    fnv1a_update_word(FnvWord::from_u128(hash), K_128, B_128, data).as_u128()
607}
608
609/// Computes the 128-bit FNV-1a hash of `data`.
610#[must_use]
611pub fn fnv1a_128(data: &[u8]) -> u128 {
612    let basis = compute_offset_basis::<16>(K_128, B_128);
613    fnv1a_update_word(basis, K_128, B_128, data).as_u128()
614}
615
616/// Computes the 128-bit FNV-1a hash of `data` using a custom `offset_basis`,
617/// per RFC 9923 Section 4.
618#[must_use]
619pub fn fnv1a_128_with_basis(offset_basis: u128, data: &[u8]) -> u128 {
620    fnv1a_128_update(offset_basis, data)
621}
622
623/// Computes the 128-bit FNV-1a hash of `data` as a lowercase hex string.
624#[must_use]
625pub fn fnv1a_128_hex(data: impl AsRef<[u8]>) -> String {
626    to_hex(&fnv1a_128(data.as_ref()).to_be_bytes())
627}
628
629// ----------------------------------------------------------------------------
630// 256-bit FNV Implementations (s=8, k=21, b=0x63)
631// ----------------------------------------------------------------------------
632
633pub(crate) const K_256: usize = 21;
634pub(crate) const B_256: u8 = 0x63;
635
636/// Computes the 256-bit FNV-0 hash of `data` as big-endian bytes.
637#[must_use]
638pub fn fnv0_256(data: &[u8]) -> [u8; 32] {
639    fnv0_update_word(FnvWord::<32>::zero(), K_256, B_256, data).to_be_bytes()
640}
641
642/// Computes the 256-bit FNV-0 hash of `data` as a lowercase hex string.
643#[must_use]
644pub fn fnv0_256_hex(data: impl AsRef<[u8]>) -> String {
645    to_hex(&fnv0_256(data.as_ref()))
646}
647
648/// Computes the 256-bit FNV-1 hash of `data` as big-endian bytes.
649#[must_use]
650pub fn fnv1_256(data: &[u8]) -> [u8; 32] {
651    let basis = compute_offset_basis::<32>(K_256, B_256);
652    fnv1_update_word(basis, K_256, B_256, data).to_be_bytes()
653}
654
655/// Computes the 256-bit FNV-1 hash of `data` as a lowercase hex string.
656#[must_use]
657pub fn fnv1_256_hex(data: impl AsRef<[u8]>) -> String {
658    to_hex(&fnv1_256(data.as_ref()))
659}
660
661/// Computes the 256-bit FNV-1a hash of `data` as big-endian bytes.
662#[must_use]
663pub fn fnv1a_256(data: &[u8]) -> [u8; 32] {
664    let basis = compute_offset_basis::<32>(K_256, B_256);
665    fnv1a_update_word(basis, K_256, B_256, data).to_be_bytes()
666}
667
668/// Computes the 256-bit FNV-1a hash of `data` as a lowercase hex string.
669#[must_use]
670pub fn fnv1a_256_hex(data: impl AsRef<[u8]>) -> String {
671    to_hex(&fnv1a_256(data.as_ref()))
672}
673
674// ----------------------------------------------------------------------------
675// 512-bit FNV Implementations (s=9, k=43, b=0x57)
676// ----------------------------------------------------------------------------
677
678pub(crate) const K_512: usize = 43;
679pub(crate) const B_512: u8 = 0x57;
680
681/// Computes the 512-bit FNV-0 hash of `data` as big-endian bytes.
682#[must_use]
683pub fn fnv0_512(data: &[u8]) -> [u8; 64] {
684    fnv0_update_word(FnvWord::<64>::zero(), K_512, B_512, data).to_be_bytes()
685}
686
687/// Computes the 512-bit FNV-0 hash of `data` as a lowercase hex string.
688#[must_use]
689pub fn fnv0_512_hex(data: impl AsRef<[u8]>) -> String {
690    to_hex(&fnv0_512(data.as_ref()))
691}
692
693/// Computes the 512-bit FNV-1 hash of `data` as big-endian bytes.
694#[must_use]
695pub fn fnv1_512(data: &[u8]) -> [u8; 64] {
696    let basis = compute_offset_basis::<64>(K_512, B_512);
697    fnv1_update_word(basis, K_512, B_512, data).to_be_bytes()
698}
699
700/// Computes the 512-bit FNV-1 hash of `data` as a lowercase hex string.
701#[must_use]
702pub fn fnv1_512_hex(data: impl AsRef<[u8]>) -> String {
703    to_hex(&fnv1_512(data.as_ref()))
704}
705
706/// Computes the 512-bit FNV-1a hash of `data` as big-endian bytes.
707#[must_use]
708pub fn fnv1a_512(data: &[u8]) -> [u8; 64] {
709    let basis = compute_offset_basis::<64>(K_512, B_512);
710    fnv1a_update_word(basis, K_512, B_512, data).to_be_bytes()
711}
712
713/// Computes the 512-bit FNV-1a hash of `data` as a lowercase hex string.
714#[must_use]
715pub fn fnv1a_512_hex(data: impl AsRef<[u8]>) -> String {
716    to_hex(&fnv1a_512(data.as_ref()))
717}
718
719// ----------------------------------------------------------------------------
720// 1024-bit FNV Implementations (s=10, k=85, b=0x8d)
721// ----------------------------------------------------------------------------
722
723pub(crate) const K_1024: usize = 85;
724pub(crate) const B_1024: u8 = 0x8d;
725
726/// Computes the 1024-bit FNV-0 hash of `data` as big-endian bytes.
727#[must_use]
728pub fn fnv0_1024(data: &[u8]) -> [u8; 128] {
729    fnv0_update_word(FnvWord::<128>::zero(), K_1024, B_1024, data).to_be_bytes()
730}
731
732/// Computes the 1024-bit FNV-0 hash of `data` as a lowercase hex string.
733#[must_use]
734pub fn fnv0_1024_hex(data: impl AsRef<[u8]>) -> String {
735    to_hex(&fnv0_1024(data.as_ref()))
736}
737
738/// Computes the 1024-bit FNV-1 hash of `data` as big-endian bytes.
739#[must_use]
740pub fn fnv1_1024(data: &[u8]) -> [u8; 128] {
741    let basis = compute_offset_basis::<128>(K_1024, B_1024);
742    fnv1_update_word(basis, K_1024, B_1024, data).to_be_bytes()
743}
744
745/// Computes the 1024-bit FNV-1 hash of `data` as a lowercase hex string.
746#[must_use]
747pub fn fnv1_1024_hex(data: impl AsRef<[u8]>) -> String {
748    to_hex(&fnv1_1024(data.as_ref()))
749}
750
751/// Computes the 1024-bit FNV-1a hash of `data` as big-endian bytes.
752#[must_use]
753pub fn fnv1a_1024(data: &[u8]) -> [u8; 128] {
754    let basis = compute_offset_basis::<128>(K_1024, B_1024);
755    fnv1a_update_word(basis, K_1024, B_1024, data).to_be_bytes()
756}
757
758/// Computes the 1024-bit FNV-1a hash of `data` as a lowercase hex string.
759#[must_use]
760pub fn fnv1a_1024_hex(data: impl AsRef<[u8]>) -> String {
761    to_hex(&fnv1a_1024(data.as_ref()))
762}
763
764// ----------------------------------------------------------------------------
765// Arbitrary-Width XOR Folding & Range Mapping (RFC 9923 Section 3)
766// ----------------------------------------------------------------------------
767
768/// Folds an FNV hash of input data to an arbitrary bit length `k_bits`
769/// (where $0 < k\_bits < 1024$), per RFC 9923 Section 3.
770pub fn fnv_xor_fold(
771    variant: FnvVariant,
772    k_bits: usize,
773    data: &[u8],
774) -> Result<Vec<u8>> {
775    if k_bits == 0 || k_bits >= 1024 {
776        bail!("k_bits must be in range 1..1024, got {k_bits}");
777    }
778    let num_bytes = k_bits.saturating_add(7) / 8;
779
780    if k_bits < 32 {
781        let h = match variant {
782            FnvVariant::Fnv0 => {
783                fnv0_update_word(FnvWord::<4>::zero(), K_32, B_32, data)
784            }
785            FnvVariant::Fnv1 | FnvVariant::Fnv1a => {
786                let basis = compute_offset_basis::<4>(K_32, B_32);
787                if variant == FnvVariant::Fnv1 {
788                    fnv1_update_word(basis, K_32, B_32, data)
789                } else {
790                    fnv1a_update_word(basis, K_32, B_32, data)
791                }
792            }
793        };
794        let shifted = h.shift_right_bits(k_bits);
795        let folded = h.xor(shifted).mask_bits(k_bits);
796        return Ok(folded.to_trimmed_be_bytes(num_bytes));
797    }
798    if k_bits < 64 {
799        let h = match variant {
800            FnvVariant::Fnv0 => {
801                fnv0_update_word(FnvWord::<8>::zero(), K_64, B_64, data)
802            }
803            FnvVariant::Fnv1 | FnvVariant::Fnv1a => {
804                let basis = compute_offset_basis::<8>(K_64, B_64);
805                if variant == FnvVariant::Fnv1 {
806                    fnv1_update_word(basis, K_64, B_64, data)
807                } else {
808                    fnv1a_update_word(basis, K_64, B_64, data)
809                }
810            }
811        };
812        let shifted = h.shift_right_bits(k_bits);
813        let folded = h.xor(shifted).mask_bits(k_bits);
814        return Ok(folded.to_trimmed_be_bytes(num_bytes));
815    }
816    if k_bits < 128 {
817        let h = match variant {
818            FnvVariant::Fnv0 => {
819                fnv0_update_word(FnvWord::<16>::zero(), K_128, B_128, data)
820            }
821            FnvVariant::Fnv1 | FnvVariant::Fnv1a => {
822                let basis = compute_offset_basis::<16>(K_128, B_128);
823                if variant == FnvVariant::Fnv1 {
824                    fnv1_update_word(basis, K_128, B_128, data)
825                } else {
826                    fnv1a_update_word(basis, K_128, B_128, data)
827                }
828            }
829        };
830        let shifted = h.shift_right_bits(k_bits);
831        let folded = h.xor(shifted).mask_bits(k_bits);
832        return Ok(folded.to_trimmed_be_bytes(num_bytes));
833    }
834    if k_bits < 256 {
835        let h = match variant {
836            FnvVariant::Fnv0 => {
837                fnv0_update_word(FnvWord::<32>::zero(), K_256, B_256, data)
838            }
839            FnvVariant::Fnv1 | FnvVariant::Fnv1a => {
840                let basis = compute_offset_basis::<32>(K_256, B_256);
841                if variant == FnvVariant::Fnv1 {
842                    fnv1_update_word(basis, K_256, B_256, data)
843                } else {
844                    fnv1a_update_word(basis, K_256, B_256, data)
845                }
846            }
847        };
848        let shifted = h.shift_right_bits(k_bits);
849        let folded = h.xor(shifted).mask_bits(k_bits);
850        return Ok(folded.to_trimmed_be_bytes(num_bytes));
851    }
852    if k_bits < 512 {
853        let h = match variant {
854            FnvVariant::Fnv0 => {
855                fnv0_update_word(FnvWord::<64>::zero(), K_512, B_512, data)
856            }
857            FnvVariant::Fnv1 | FnvVariant::Fnv1a => {
858                let basis = compute_offset_basis::<64>(K_512, B_512);
859                if variant == FnvVariant::Fnv1 {
860                    fnv1_update_word(basis, K_512, B_512, data)
861                } else {
862                    fnv1a_update_word(basis, K_512, B_512, data)
863                }
864            }
865        };
866        let shifted = h.shift_right_bits(k_bits);
867        let folded = h.xor(shifted).mask_bits(k_bits);
868        return Ok(folded.to_trimmed_be_bytes(num_bytes));
869    }
870
871    let h = match variant {
872        FnvVariant::Fnv0 => {
873            fnv0_update_word(FnvWord::<128>::zero(), K_1024, B_1024, data)
874        }
875        FnvVariant::Fnv1 | FnvVariant::Fnv1a => {
876            let basis = compute_offset_basis::<128>(K_1024, B_1024);
877            if variant == FnvVariant::Fnv1 {
878                fnv1_update_word(basis, K_1024, B_1024, data)
879            } else {
880                fnv1a_update_word(basis, K_1024, B_1024, data)
881            }
882        }
883    };
884    let shifted = h.shift_right_bits(k_bits);
885    let folded = h.xor(shifted).mask_bits(k_bits);
886    Ok(folded.to_trimmed_be_bytes(num_bytes))
887}
888
889/// Folds an FNV-1a hash of input data to an arbitrary bit length $k \le 64$.
890pub fn fnv1a_fold_u64(k_bits: usize, data: &[u8]) -> Result<u64> {
891    if k_bits == 0 || k_bits > 64 {
892        bail!("k_bits must be in range 1..=64, got {k_bits}");
893    }
894    let bytes = fnv_xor_fold(FnvVariant::Fnv1a, k_bits, data)?;
895    let mut val: u64 = 0;
896    for b in bytes {
897        val = (val << 8) | u64::from(b);
898    }
899    Ok(val)
900}
901
902/// Computes the 16-bit FNV-1a hash of `data` via XOR-folding from 32 bits.
903#[must_use]
904#[expect(
905    clippy::expect_used,
906    reason = "folded is masked with 0xffff so it is provably guaranteed to fit in u16"
907)]
908pub fn fnv1a_16(data: &[u8]) -> u16 {
909    let h = fnv1a_32(data);
910    let folded = (h ^ (h >> 16)) & 0xffff;
911    u16::try_from(folded).expect("folded masked with 0xffff fits in u16")
912}
913
914/// Computes the 16-bit FNV-1a hash of `data` as a lowercase hex string.
915#[must_use]
916pub fn fnv1a_16_hex(data: impl AsRef<[u8]>) -> String {
917    to_hex(&fnv1a_16(data.as_ref()).to_be_bytes())
918}
919
920/// Computes the 24-bit FNV-1a hash of `data` via XOR-folding from 32 bits.
921#[must_use]
922pub fn fnv1a_24(data: &[u8]) -> u32 {
923    let h = fnv1a_32(data);
924    (h ^ (h >> 24)) & 0x00ff_ffff
925}
926
927/// Computes the 24-bit FNV-1a hash of `data` as a lowercase hex string.
928#[must_use]
929#[expect(
930    clippy::expect_used,
931    reason = "be has 4 bytes so slice from index 1 is provably non-empty and valid"
932)]
933pub fn fnv1a_24_hex(data: impl AsRef<[u8]>) -> String {
934    let val = fnv1a_24(data.as_ref());
935    let be = val.to_be_bytes();
936    to_hex(be.get(1..).expect("be has 4 bytes"))
937}
938
939/// Computes the 48-bit FNV-1a hash of `data` via XOR-folding from 64 bits.
940#[must_use]
941pub fn fnv1a_48(data: &[u8]) -> u64 {
942    let h = fnv1a_64(data);
943    (h ^ (h >> 48)) & 0x0000_ffff_ffff_ffff
944}
945
946/// Computes the 48-bit FNV-1a hash of `data` as a lowercase hex string.
947#[must_use]
948#[expect(
949    clippy::expect_used,
950    reason = "be has 8 bytes so slice from index 2 is provably non-empty and valid"
951)]
952pub fn fnv1a_48_hex(data: impl AsRef<[u8]>) -> String {
953    let val = fnv1a_48(data.as_ref());
954    let be = val.to_be_bytes();
955    to_hex(be.get(2..).expect("be has 8 bytes"))
956}
957
958/// Maps `data` to a value in `0..=max` using 64-bit FNV-1a with retry-based
959/// modulo bias avoidance, per RFC 9923 Section 3.
960#[must_use]
961#[expect(
962    clippy::expect_used,
963    reason = "max_plus_1 is checked to be >= 2 and rem < max_plus_1 <= u64::MAX so rem fits in u64"
964)]
965pub fn fnv1a_range_u64(max: u64, data: &[u8]) -> u64 {
966    if max == u64::MAX {
967        return fnv1a_64(data);
968    }
969    let max_plus_1 = u128::from(max).saturating_add(1);
970    if max_plus_1 <= 1 {
971        return 0;
972    }
973    // S = 64, so 2^S - 1 = u64::MAX per RFC 9923 Section 3 formula:
974    // X = int((2**S - 1) / (max + 1)) * (max + 1)
975    let two_to_s_minus_1 = u128::from(u64::MAX);
976    let quotient = two_to_s_minus_1.checked_div(max_plus_1).expect(
977        "max_plus_1 is checked to be >= 2 so division cannot divide by zero",
978    );
979    let x_limit = quotient.wrapping_mul(max_plus_1);
980    let x_limit_u64 = u64::try_from(x_limit)
981        .expect("x_limit <= 2^64 - 1 is guaranteed to fit in u64");
982    let mut h = fnv1a_64(data);
983    let offset = compute_offset_basis::<8>(K_64, B_64).as_u64();
984    let prime: u64 = 0x0100_0000_01b3;
985    while h >= x_limit_u64 {
986        h = h.wrapping_mul(prime).wrapping_add(offset);
987    }
988    let rem = u128::from(h)
989        .checked_rem(max_plus_1)
990        .expect("max_plus_1 is >= 2 so checked_rem cannot divide by zero");
991    u64::try_from(rem).expect("rem < max_plus_1 <= u64::MAX fits in u64")
992}
993
994/// Maps `data` to a value in `0..=max` using 32-bit FNV-1a with retry-based
995/// modulo bias avoidance, per RFC 9923 Section 3.
996#[must_use]
997#[expect(
998    clippy::expect_used,
999    reason = "max_plus_1 is checked to be >= 2 and rem < max_plus_1 <= u32::MAX so rem fits in u32"
1000)]
1001pub fn fnv1a_range_u32(max: u32, data: &[u8]) -> u32 {
1002    if max == u32::MAX {
1003        return fnv1a_32(data);
1004    }
1005    let max_plus_1 = u64::from(max).saturating_add(1);
1006    if max_plus_1 <= 1 {
1007        return 0;
1008    }
1009    // S = 32, so 2^S - 1 = u32::MAX per RFC 9923 Section 3 formula:
1010    // X = int((2**S - 1) / (max + 1)) * (max + 1)
1011    let two_to_s_minus_1 = u64::from(u32::MAX);
1012    let quotient = two_to_s_minus_1.checked_div(max_plus_1).expect(
1013        "max_plus_1 is checked to be >= 2 so division cannot divide by zero",
1014    );
1015    let x_limit = quotient.wrapping_mul(max_plus_1);
1016    let x_limit_u32 = u32::try_from(x_limit)
1017        .expect("x_limit <= 2^32 - 1 is guaranteed to fit in u32");
1018    let mut h = fnv1a_32(data);
1019    let offset = compute_offset_basis::<4>(K_32, B_32).as_u32();
1020    let prime: u32 = 0x0100_0193;
1021    while h >= x_limit_u32 {
1022        h = h.wrapping_mul(prime).wrapping_add(offset);
1023    }
1024    let rem = u64::from(h)
1025        .checked_rem(max_plus_1)
1026        .expect("max_plus_1 is >= 2 so checked_rem cannot divide by zero");
1027    u32::try_from(rem).expect("rem < max_plus_1 <= u32::MAX fits in u32")
1028}
1029
1030// ----------------------------------------------------------------------------
1031// Runtime FNV Prime Search & Verification (RFC 9923 Section 2.1)
1032// ----------------------------------------------------------------------------
1033
1034/// Discovers the smallest prime parameter `b` for power-of-two size $2^s$
1035/// ($s \in [5, 10]$) satisfying the RFC 9923 Section 2.1 constraints:
1036/// 1. $0 < b < 256$
1037/// 2. $b.\text{count\_ones}() \in \{4, 5\}$
1038/// 3. $(p \pmod{2^{40} - 2^{24} - 1}) > (2^{24} + 2^8 + 2^7)$
1039/// 4. $p = 256^k + 2^8 + b$ is prime.
1040#[expect(
1041    clippy::arithmetic_side_effects,
1042    reason = "Unbounded big-integer Natural addition cannot overflow"
1043)]
1044pub fn find_fnv_prime_param(s: usize) -> Result<u8> {
1045    if !(5..=10).contains(&s) {
1046        bail!("s must be in range 5..=10, got {s}");
1047    }
1048    let k = (5_usize.saturating_add(1_usize << s)) / 12_usize;
1049    let m: u64 = (1_u64 << 40).wrapping_sub(1_u64 << 24).wrapping_sub(1);
1050    ensure!(m > 0, "Modulo m must be non-zero");
1051    let bound: u64 = (1_u64 << 24)
1052        .wrapping_add(1_u64 << 8)
1053        .wrapping_add(1_u64 << 7);
1054    let m_u128 = u128::from(m);
1055
1056    // Compute 256^k mod M using u128 wrapping arithmetic
1057    let mut pow_256_k: u64 = 1;
1058    let base_256: u64 = 256;
1059    let mut exp = k;
1060    let mut cur_base = base_256;
1061    while exp > 0 {
1062        if exp & 1 == 1 {
1063            let prod = u128::from(pow_256_k).wrapping_mul(u128::from(cur_base));
1064            let rem = prod
1065                .checked_rem(m_u128)
1066                .context("Modulo division by zero")?;
1067            pow_256_k = u64::try_from(rem)?;
1068        }
1069        let sq = u128::from(cur_base).wrapping_mul(u128::from(cur_base));
1070        let rem = sq.checked_rem(m_u128).context("Modulo division by zero")?;
1071        cur_base = u64::try_from(rem)?;
1072        exp >>= 1;
1073    }
1074
1075    let k_bits = u32::try_from(k.saturating_mul(8))?;
1076    let base_nat =
1077        (Natural::from(1_u32) << k_bits) + (Natural::from(1_u32) << 8_u32);
1078
1079    for b in 1_u8..=255_u8 {
1080        let ones = b.count_ones();
1081        if ones != 4 && ones != 5 {
1082            continue;
1083        }
1084        let sum_val = pow_256_k.wrapping_add(256).wrapping_add(u64::from(b));
1085        let p_mod_m =
1086            sum_val.checked_rem(m).context("Modulo division by zero")?;
1087        if p_mod_m <= bound {
1088            continue;
1089        }
1090        let cand = &base_nat + Natural::from(b);
1091        if ctb_formats_math::primality::is_prime_natural(&cand) {
1092            return Ok(b);
1093        }
1094    }
1095    bail!("No FNV prime parameter found for s={s}")
1096}
1097
1098// ----------------------------------------------------------------------------
1099// Backward-compatibility Aliases
1100// ----------------------------------------------------------------------------
1101
1102/// Alias for [`fnv1a_32`].
1103#[must_use]
1104pub fn fnv1a32(data: &[u8]) -> u32 {
1105    fnv1a_32(data)
1106}
1107
1108/// Alias for [`fnv1a_64`].
1109#[must_use]
1110pub fn fnv1a64(data: &[u8]) -> u64 {
1111    fnv1a_64(data)
1112}
1113
1114/// Alias for [`fnv1a_32_hex`].
1115#[must_use]
1116pub fn fnv1a32_hex(data: impl AsRef<[u8]>) -> String {
1117    fnv1a_32_hex(data)
1118}
1119
1120/// Alias for [`fnv1a_64_hex`].
1121#[must_use]
1122pub fn fnv1a64_hex(data: impl AsRef<[u8]>) -> String {
1123    fnv1a_64_hex(data)
1124}
1125
1126/// Alias for [`fnv1a_32_update`].
1127#[must_use]
1128pub fn fnv1a32_update(hash: u32, data: &[u8]) -> u32 {
1129    fnv1a_32_update(hash, data)
1130}
1131
1132/// Alias for [`fnv1a_64_update`].
1133#[must_use]
1134pub fn fnv1a64_update(hash: u64, data: &[u8]) -> u64 {
1135    fnv1a_64_update(hash, data)
1136}
1137
1138#[cfg(test)]
1139#[allow(
1140    clippy::panic,
1141    clippy::expect_used,
1142    clippy::unwrap_used,
1143    clippy::unwrap_in_result,
1144    clippy::panic_in_result_fn,
1145    clippy::indexing_slicing,
1146    clippy::arithmetic_side_effects,
1147    reason = "Standard repository test boilerplate"
1148)]
1149mod tests {
1150    use super::*;
1151
1152    #[crate::ctb_test]
1153    fn test_offset_basis_derivation_from_signature() {
1154        // Test that computing FNV-0 on FNV_BASIS_STRING derives the exact
1155        // offset_basis constants specified in RFC 9923 Section 5.
1156        let basis32 = compute_offset_basis::<4>(K_32, B_32).as_u32();
1157        assert_eq!(basis32, 0x811c_9dc5);
1158
1159        let basis64 = compute_offset_basis::<8>(K_64, B_64).as_u64();
1160        assert_eq!(basis64, 0xcbf2_9ce4_8422_2325);
1161
1162        let basis128 = compute_offset_basis::<16>(K_128, B_128).as_u128();
1163        assert_eq!(basis128, 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d);
1164
1165        let basis256_hex = compute_offset_basis::<32>(K_256, B_256).to_hex();
1166        assert_eq!(
1167            basis256_hex,
1168            "dd268dbcaac550362d98c384c4e576ccc8b1536847b6bbb31023b4c8caee0535"
1169        );
1170
1171        let basis512_hex = compute_offset_basis::<64>(K_512, B_512).to_hex();
1172        assert_eq!(
1173            basis512_hex,
1174            "b86db0b1171f4416dca1e50f309990acac87d059c90000000000000000000d21\
1175             e948f68a34c192f62ea79bc942dbe7ce182036415f56e34bac982aac4afe9fd9"
1176        );
1177
1178        let basis1024_hex =
1179            compute_offset_basis::<128>(K_1024, B_1024).to_hex();
1180        assert_eq!(
1181            basis1024_hex,
1182            "0000000000000000005f7a76758ecc4d32e56d5a591028b74b29fc4223fdada1\
1183             6c3bf34eda3674da9a21d9000000000000000000000000000000000000000000\
1184             000000000000000000000000000000000000000000000000000000000004c6d7\
1185             eb6e73802734510a555f256cc005ae556bde8cc9c6a93b21aff4b16c71ee90b3"
1186        );
1187    }
1188
1189    #[crate::ctb_test]
1190    fn test_fnv1a_known_vectors() {
1191        assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325);
1192        assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
1193        assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
1194        assert_eq!(fnv1a64_hex(b"foobar"), "85944171f73967e8");
1195        assert_eq!(fnv1a_64(b"Hello!\x01\xff\xed"), 0xbd51_ea70_94ee_6fa1);
1196
1197        assert_eq!(fnv1a_32(b""), 0x811c_9dc5);
1198        assert_eq!(fnv1a_32(b"a"), 0xe40c_292c);
1199        assert_eq!(fnv1a_32(b"foobar"), 0xbf9c_f968);
1200        assert_eq!(fnv1a32_hex(b"foobar"), "bf9cf968");
1201        assert_eq!(fnv1a_32(b"Hello!\x01\xff\xed"), 0xfd9d_3881);
1202
1203        // Official RFC 9923 test vectors from Section 8.3 (main.c) for larger sizes
1204        assert_eq!(
1205            fnv1a_128_hex(b"foobar"),
1206            "343e1662793c64bf6f0d3597ba446f18"
1207        );
1208        assert_eq!(
1209            fnv1a_256_hex(b"foobar"),
1210            "b055ea2f306cadad4f0f81c02d3889dc32453dad5ae35b753ba1a91084af3428"
1211        );
1212        assert_eq!(
1213            fnv1a_512_hex(b"foobar"),
1214            "b0ec738d9c6fd969d05f0b35f6c0ed53adcacccd8e0000004bf99f58ee4196af\
1215             b9700e20110830fea5396b76280e47fd022b6e81331ca1a9ced729c364be7788"
1216        );
1217        assert_eq!(
1218            fnv1a_1024_hex(b"foobar"),
1219            "00000631175fa7ae643ad08723d312c9fd024adb91f77f6b19587197a22bcdf2\
1220             3727166c4572d0b985d5ae000000000000000000000000000000000000000000\
1221             00000000000000000000000000000000000000000000004270d11ef418ef08b8\
1222             a49e1e825e547eb39937f819222f3b7fc92a0e4707900888847a554bacec98b0"
1223        );
1224    }
1225
1226    #[crate::ctb_test]
1227    fn test_rfc9923_section_2_3_serialization() {
1228        let word32 = FnvWord::from_u32(fnv1a_32(b"foobar"));
1229        assert_eq!(word32.to_be_bytes(), [0xbf, 0x9c, 0xf9, 0x68]);
1230        assert_eq!(word32.to_le_bytes(), [0x68, 0xf9, 0x9c, 0xbf]);
1231
1232        let word64 = FnvWord::from_u64(fnv1a_64(b"foobar"));
1233        assert_eq!(
1234            word64.to_be_bytes(),
1235            [0x85, 0x94, 0x41, 0x71, 0xf7, 0x39, 0x67, 0xe8]
1236        );
1237        assert_eq!(
1238            word64.to_le_bytes(),
1239            [0xe8, 0x67, 0x39, 0xf7, 0x71, 0x41, 0x94, 0x85]
1240        );
1241
1242        let word128 = fnv1a_update_word(
1243            compute_offset_basis::<16>(K_128, B_128),
1244            K_128,
1245            B_128,
1246            b"foobar",
1247        );
1248        assert_eq!(word128.to_be_bytes(), fnv1a_128(b"foobar").to_be_bytes());
1249        assert_eq!(
1250            word128.to_le_bytes(),
1251            [
1252                0x18, 0x6f, 0x44, 0xba, 0x97, 0x35, 0x0d, 0x6f, 0xbf, 0x64,
1253                0x3c, 0x79, 0x62, 0x16, 0x3e, 0x34,
1254            ]
1255        );
1256
1257        let word256 = fnv1a_update_word(
1258            compute_offset_basis::<32>(K_256, B_256),
1259            K_256,
1260            B_256,
1261            b"foobar",
1262        );
1263        let mut expected256_le = fnv1a_256(b"foobar");
1264        expected256_le.reverse();
1265        assert_eq!(word256.to_be_bytes(), fnv1a_256(b"foobar"));
1266        assert_eq!(word256.to_le_bytes(), expected256_le);
1267
1268        let word512 = fnv1a_update_word(
1269            compute_offset_basis::<64>(K_512, B_512),
1270            K_512,
1271            B_512,
1272            b"foobar",
1273        );
1274        let mut expected512_le = fnv1a_512(b"foobar");
1275        expected512_le.reverse();
1276        assert_eq!(word512.to_be_bytes(), fnv1a_512(b"foobar"));
1277        assert_eq!(word512.to_le_bytes(), expected512_le);
1278
1279        let word1024 = fnv1a_update_word(
1280            compute_offset_basis::<128>(K_1024, B_1024),
1281            K_1024,
1282            B_1024,
1283            b"foobar",
1284        );
1285        let mut expected1024_le = fnv1a_1024(b"foobar");
1286        expected1024_le.reverse();
1287        assert_eq!(word1024.to_be_bytes(), fnv1a_1024(b"foobar"));
1288        assert_eq!(word1024.to_le_bytes(), expected1024_le);
1289    }
1290
1291    #[crate::ctb_test]
1292    fn test_fnv0_and_fnv1_basics() {
1293        // FNV-0 of empty string is 0
1294        assert_eq!(fnv0_32(b""), 0);
1295        assert_eq!(fnv0_64(b""), 0);
1296        assert_eq!(fnv0_128(b""), 0);
1297
1298        // FNV-1 of empty string is offset_basis
1299        assert_eq!(fnv1_32(b""), 0x811c_9dc5);
1300        assert_eq!(fnv1_64(b""), 0xcbf2_9ce4_8422_2325);
1301
1302        // FNV-1 vs FNV-1a differ on non-empty input
1303        assert_ne!(fnv1_32(b"foobar"), fnv1a_32(b"foobar"));
1304        assert_ne!(fnv1_64(b"foobar"), fnv1a_64(b"foobar"));
1305    }
1306
1307    #[crate::ctb_test]
1308    fn test_streaming_equivalence() {
1309        let mut stream = FnvStream::<8>::new(FnvVariant::Fnv1a, K_64, B_64);
1310        stream.update(b"foo");
1311        stream.update(b"bar");
1312        assert_eq!(stream.finalize().as_u64(), fnv1a_64(b"foobar"));
1313    }
1314
1315    #[crate::ctb_test]
1316    fn test_xor_folding() {
1317        let folded16 = fnv1a_16(b"foobar");
1318        assert_eq!(fnv1a_16_hex(b"foobar"), format!("{folded16:04x}"));
1319
1320        let folded24 = fnv1a_24(b"foobar");
1321        assert_eq!(fnv1a_24_hex(b"foobar"), format!("{folded24:06x}"));
1322
1323        let folded48 = fnv1a_48(b"foobar");
1324        assert_eq!(fnv1a_48_hex(b"foobar"), format!("{folded48:012x}"));
1325
1326        let arbitrary = fnv_xor_fold(FnvVariant::Fnv1a, 20, b"foobar").unwrap();
1327        assert_eq!(arbitrary.len(), 3);
1328
1329        let u64_fold = fnv1a_fold_u64(24, b"foobar").unwrap();
1330        assert_eq!(u64_fold, u64::from(folded24));
1331    }
1332
1333    #[crate::ctb_test]
1334    fn test_range_mapping() {
1335        let val = fnv1a_range_u64(100, b"foobar");
1336        assert!(val <= 100);
1337
1338        let val_max = fnv1a_range_u64(u64::MAX, b"foobar");
1339        assert_eq!(val_max, fnv1a_64(b"foobar"));
1340
1341        let val32 = fnv1a_range_u32(100, b"foobar");
1342        assert!(val32 <= 100);
1343
1344        let val32_max = fnv1a_range_u32(u32::MAX, b"foobar");
1345        assert_eq!(val32_max, fnv1a_32(b"foobar"));
1346
1347        // Verify that retry iteration correctly modifies values >= X
1348        let max_val: u32 = 4;
1349        let mut found = false;
1350        for i in 0_u32..500 {
1351            let res = fnv1a_range_u32(max_val, &i.to_le_bytes());
1352            assert!(res <= max_val);
1353            if res == 0 {
1354                found = true;
1355            }
1356        }
1357        assert!(found);
1358    }
1359
1360    #[crate::ctb_test]
1361    fn test_rfc9923_section_4_multi_value_chaining() {
1362        // RFC 9923 Section 4: hashing concatenations matches chaining via offset_basis
1363        let x = b"hello ";
1364        let y = b"world";
1365        let z = b"!";
1366        let combined = b"hello world!";
1367
1368        let h_combined = fnv1a_64(combined);
1369        let h_x = fnv1a_64(x);
1370        let h_xy = fnv1a_64_with_basis(h_x, y);
1371        let h_xyz = fnv1a_64_with_basis(h_xy, z);
1372        assert_eq!(h_combined, h_xyz);
1373
1374        let h32_combined = fnv1a_32(combined);
1375        let h32_x = fnv1a_32(x);
1376        let h32_xy = fnv1a_32_with_basis(h32_x, y);
1377        let h32_xyz = fnv1a_32_with_basis(h32_xy, z);
1378        assert_eq!(h32_combined, h32_xyz);
1379
1380        let h128_combined = fnv1a_128(combined);
1381        let h128_x = fnv1a_128(x);
1382        let h128_xy = fnv1a_128_with_basis(h128_x, y);
1383        let h128_xyz = fnv1a_128_with_basis(h128_xy, z);
1384        assert_eq!(h128_combined, h128_xyz);
1385    }
1386
1387    #[crate::ctb_test]
1388    fn test_rfc9923_section_2_2_empty_string_basis() {
1389        // RFC 9923 Section 2.2: hashing the null string yields the offset_basis
1390        assert_eq!(
1391            fnv1a_128(b""),
1392            compute_offset_basis::<16>(K_128, B_128).as_u128()
1393        );
1394        assert_eq!(
1395            fnv1a_256(b""),
1396            compute_offset_basis::<32>(K_256, B_256).to_be_bytes()
1397        );
1398        assert_eq!(
1399            fnv1a_512(b""),
1400            compute_offset_basis::<64>(K_512, B_512).to_be_bytes()
1401        );
1402        assert_eq!(
1403            fnv1a_1024(b""),
1404            compute_offset_basis::<128>(K_1024, B_1024).to_be_bytes()
1405        );
1406    }
1407
1408    #[crate::ctb_test]
1409    fn test_runtime_prime_param_discovery() {
1410        assert_eq!(find_fnv_prime_param(5).unwrap(), 0x93);
1411        assert_eq!(find_fnv_prime_param(6).unwrap(), 0xb3);
1412        assert_eq!(find_fnv_prime_param(7).unwrap(), 0x3b);
1413        assert_eq!(find_fnv_prime_param(8).unwrap(), 0x63);
1414        assert_eq!(find_fnv_prime_param(9).unwrap(), 0x57);
1415        assert_eq!(find_fnv_prime_param(10).unwrap(), 0x8d);
1416    }
1417}