aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Optimized hasher for unique integer keys.
//!
//! This module provides [`IdentityHasher`], a hasher that passes through integer values
//! unchanged. It is intended for use with `HashMap` and `HashSet` where the keys
//! are already high-quality unique identifiers (like `NodeId`, `EdgeId`, or `InternedString`),
//! avoiding the unnecessary overhead of hashing (SipHash).
//!
//! # The Story of IdentityHasher
//!
//! In a database engine, we frequently use HashMaps and HashSets to look up entities
//! by their unique integer IDs. The default Rust hasher (SipHash) is designed to protect
//! against HashDoS attacks by scrambling the bits using a cryptographic algorithm.
//!
//! However, when our keys are already randomly distributed 64-bit integers generated
//! internally (like a `NodeId` or `EdgeId`), hashing them *again* provides zero benefit
//! and costs valuable CPU cycles.
//!
//! [`IdentityHasher`] bypasses this overhead by simply taking the integer key and using
//! it directly as the hash value. This single optimization saves a significant amount
//! of CPU time during massive graph traversals and index lookups.
//!
//! # Safety Warning
//!
//! **Do not use this hasher for maps exposed to untrusted user input.**
//! It is intentionally vulnerable to HashDoS attacks. Only use it for internal identifiers
//! or data where collisions cannot be maliciously crafted.
//!
//! # Examples
//!
//! ```rust
//! use std::collections::HashMap;
//! use std::hash::BuildHasherDefault;
//! use aletheiadb::core::hasher::IdentityHasher;
//!
//! // Create a HashMap optimized for integer keys
//! let mut map: HashMap<u64, String, BuildHasherDefault<IdentityHasher>> =
//!     HashMap::with_hasher(BuildHasherDefault::default());
//!
//! map.insert(42, "meaning of life".to_string());
//! ```

use std::hash::Hasher;

const FNV_PRIME: u64 = 0x100000001b3;
const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;

/// A highly optimized hasher for pre-hashed or unique integer keys.
///
/// This hasher implements a "pass-through" strategy for `u64` and `u32` values,
/// treating the input integer directly as the hash code. This eliminates the
/// CPU overhead of cryptographic hash functions (like SipHash) when the keys
/// are already high-quality random identifiers (e.g., `NodeId`, `EdgeId`, `InternedString`).
///
/// # Performance
///
/// - **Integers**: O(1), single instruction (move).
/// - **Strings/Bytes**: Fallback to FNV-1a (slower, but provided for safety).
///
/// # Safety
///
/// This hasher is **not** resistant to HashDoS attacks. It should only be used
/// with internal IDs or trusted input. Do not use this for `HashMap`s exposed
/// to untrusted user input where keys could be crafted to cause collisions.
///
/// # Examples
///
/// ```rust
/// use std::collections::HashMap;
/// use std::hash::BuildHasherDefault;
/// use aletheiadb::core::hasher::IdentityHasher;
///
/// // Create a HashMap optimized for integer keys
/// let mut map: HashMap<u64, String, BuildHasherDefault<IdentityHasher>> =
///     HashMap::with_hasher(BuildHasherDefault::default());
///
/// map.insert(42, "meaning of life".to_string());
/// ```
#[derive(Default)]
pub struct IdentityHasher(u64);

impl IdentityHasher {
    /// Mixes a new value into the internal state.
    ///
    /// The goal of `update_state` is to handle both single-value hashing (like
    /// hashing a single `u64`) and composite hashing (like a struct with multiple fields).
    ///
    /// - **Single Value (Fast Path)**: If this is the first value written (`self.0 == 0`),
    ///   it simply overwrites the state. This means `hash(42)` is exactly `42`.
    /// - **Composite Value (Mixing)**: If the state is already dirty, it XORs the new
    ///   value and multiplies by `FNV_PRIME`. This ensures that `hash((1, 2))` is not
    ///   the same as `hash((2, 1))` or `hash(3)`, preventing catastrophic collisions
    ///   when hashing tuples or structs.
    ///
    /// # Arguments
    ///
    /// * `val` - The 64-bit integer to mix into the current hash state.
    #[inline]
    fn update_state(&mut self, val: u64) {
        if self.0 == 0 {
            // Initial state: overwrite to maintain Identity behavior for single keys
            self.0 = val;
        } else {
            // Already dirty: mix new value to avoid collisions for composite keys
            // (e.g. String which writes bytes then 0xFF marker)
            self.0 ^= val;
            self.0 = self.0.wrapping_mul(FNV_PRIME);
        }
    }
}

impl Hasher for IdentityHasher {
    /// Writes a slice of bytes into the hasher.
    ///
    /// While [`IdentityHasher`] is optimized for single integer writes (e.g., [`Self::write_u64`]),
    /// it must correctly handle arbitrary byte slices to satisfy the [`Hasher`] trait.
    ///
    /// # Implementation Details
    ///
    /// - **Fast Paths**: Byte slices of exactly 1, 2, 4, 8, or 16 bytes are cast directly
    ///   to their corresponding integer types and mixed into the state.
    /// - **Fallback**: For any other length (e.g., strings), the hasher falls back to a
    ///   standard FNV-1a algorithm. This is significantly slower but guarantees correctness
    ///   and avoids collisions.
    ///
    /// # Panics
    ///
    /// This function does not panic. The internal conversions from byte slices
    /// to integers use exact length checks.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::hash::Hasher;
    /// use aletheiadb::core::hasher::IdentityHasher;
    ///
    /// let mut hasher = IdentityHasher::default();
    ///
    /// // Fast path for 8 bytes
    /// hasher.write(&42u64.to_le_bytes());
    /// assert_eq!(hasher.finish(), 42);
    ///
    /// // Fallback path for strings
    /// let mut string_hasher = IdentityHasher::default();
    /// string_hasher.write(b"hello world");
    /// assert_ne!(string_hasher.finish(), 0);
    /// ```
    fn write(&mut self, bytes: &[u8]) {
        // Fallback for types that don't call write_u32/write_u64 directly.
        match bytes.len() {
            1 => self.update_state(bytes[0] as u64),
            2 => {
                // SAFETY: length checked
                let arr: [u8; 2] = bytes.try_into().unwrap();
                self.update_state(u16::from_le_bytes(arr) as u64);
            }
            4 => {
                // SAFETY: length checked
                let arr: [u8; 4] = bytes.try_into().unwrap();
                self.update_state(u32::from_le_bytes(arr) as u64);
            }
            8 => {
                // SAFETY: length checked
                let arr: [u8; 8] = bytes.try_into().unwrap();
                self.update_state(u64::from_le_bytes(arr));
            }
            16 => {
                // Mix high and low parts for u128 to minimize collisions
                // while keeping it deterministic
                let low_arr: [u8; 8] = bytes[0..8].try_into().unwrap();
                let high_arr: [u8; 8] = bytes[8..16].try_into().unwrap();
                let low = u64::from_le_bytes(low_arr);
                let high = u64::from_le_bytes(high_arr);
                self.update_state(low ^ high);
            }
            _ => {
                // Fallback for non-integer types (e.g. strings, large integers)
                // Use a simple FNV-1a hash to avoid collisions.

                // WARN: IdentityHasher is intended for primitive integers. Using it
                // with strings or other types is sub-optimal but we must provide
                // a valid hash to ensure correctness (no collisions).

                // If state is 0, start with FNV basis. If already dirty, chain it.
                if self.0 == 0 {
                    self.0 = FNV_OFFSET_BASIS;
                }

                for byte in bytes {
                    self.0 ^= *byte as u64;
                    self.0 = self.0.wrapping_mul(FNV_PRIME);
                }
            }
        }
    }

    /// Writes a single `u8` into the hasher.
    ///
    /// Casts the value to `u64` and mixes it into the state.
    #[inline]
    fn write_u8(&mut self, i: u8) {
        self.update_state(i as u64);
    }

    /// Writes a single `u16` into the hasher.
    ///
    /// Casts the value to `u64` and mixes it into the state.
    #[inline]
    fn write_u16(&mut self, i: u16) {
        self.update_state(i as u64);
    }

    /// Writes a single `u32` into the hasher.
    ///
    /// Casts the value to `u64` and mixes it into the state.
    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.update_state(i as u64);
    }

    /// Writes a single `u64` into the hasher.
    ///
    /// This is the primary "happy path" for the [`IdentityHasher`]. It mixes
    /// the value directly into the state. If this is the only value written
    /// to the hasher, `finish()` will return `i` exactly.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::hash::Hasher;
    /// use aletheiadb::core::hasher::IdentityHasher;
    ///
    /// let mut hasher = IdentityHasher::default();
    /// hasher.write_u64(999);
    /// assert_eq!(hasher.finish(), 999);
    /// ```
    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.update_state(i);
    }

    /// Writes a single `usize` into the hasher.
    ///
    /// Casts the value to `u64` and mixes it into the state.
    #[inline]
    fn write_usize(&mut self, i: usize) {
        self.update_state(i as u64);
    }

    /// Returns the computed hash value.
    ///
    /// If the hasher was fed a single integer, this will return that exact integer.
    /// If multiple values were fed, it will return the mixed composite hash.
    #[inline]
    fn finish(&self) -> u64 {
        self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::hash::{Hash, Hasher};

    #[test]
    fn test_identity_hasher_u32() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u32(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_composite_writes() {
        let mut h = IdentityHasher::default();
        h.write_u64(1);
        h.write_u64(2);

        // Should NOT be 2 (overwrite)
        assert_ne!(h.finish(), 2, "Hasher should mix values, not overwrite");

        // Expected: (1 ^ 2) * FNV_PRIME
        // write(1): self.0 = 1.
        // write(2): self.0 = (1 ^ 2) * FNV_PRIME = 3 * FNV_PRIME.
        let expected = 3u64.wrapping_mul(FNV_PRIME);
        assert_eq!(h.finish(), expected);
    }

    #[test]
    fn test_identity_hasher_bitwise_update_logic() {
        let mut h = IdentityHasher::default();
        h.update_state(42);
        assert_eq!(h.finish(), 42);

        h.update_state(7);
        // Correct is bitwise XOR: (42 ^ 7) * FNV_PRIME = 45 * FNV_PRIME
        let expected = 45u64.wrapping_mul(FNV_PRIME);
        assert_eq!(h.finish(), expected);

        let mut h2 = IdentityHasher::default();
        h2.update_state(1);
        assert_eq!(h2.finish(), 1);
    }

    #[test]
    fn test_identity_hasher_write_length_variations() {
        // Assert exactly what happens for specific sized writes
        let mut h1 = IdentityHasher::default();
        h1.write(&[0x12]);
        assert_eq!(h1.finish(), 0x12);

        let mut h2 = IdentityHasher::default();
        h2.write(&[0x12, 0x34]);
        assert_eq!(h2.finish(), 0x3412);

        let mut h4 = IdentityHasher::default();
        h4.write(&[0x12, 0x34, 0x56, 0x78]);
        assert_eq!(h4.finish(), 0x78563412);

        let mut h8 = IdentityHasher::default();
        h8.write(&[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]);
        assert_eq!(h8.finish(), 0xF0DEBC9A78563412);

        let mut h16 = IdentityHasher::default();
        h16.write(&[
            0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE,
            0xFF, 0x00,
        ]);
        let low = 0x8877665544332211u64;
        let high = 0x00FFEEDDCCBBAA99u64;
        assert_eq!(h16.finish(), low ^ high);
    }

    #[test]
    fn test_identity_hasher_empty_and_fallback_states() {
        let mut hasher = IdentityHasher::default();
        hasher.write(&[]);
        // Explicitly assert it doesn't default to 0
        assert_ne!(hasher.finish(), 0);

        // Fallback for an unhandled byte length (e.g. 3) does not collision
        let mut h3 = IdentityHasher::default();
        h3.write(&[0x01, 0x02, 0x03]);
        let h3_val = h3.finish();
        assert_ne!(h3_val, 0);

        // Dirty FNV chaining
        let mut h3_dirty = IdentityHasher::default();
        h3_dirty.update_state(0x42);
        h3_dirty.write(&[0x01, 0x02, 0x03]);
        assert_ne!(h3_dirty.finish(), h3_val);
    }

    #[test]
    fn test_identity_hasher_exact_primitives() {
        let mut h8 = IdentityHasher::default();
        h8.write_u8(1);
        assert_eq!(h8.finish(), 1);

        let mut h16 = IdentityHasher::default();
        h16.write_u16(2);
        assert_eq!(h16.finish(), 2);

        let mut h32 = IdentityHasher::default();
        h32.write_u32(3);
        assert_eq!(h32.finish(), 3);

        let mut h64 = IdentityHasher::default();
        h64.write_u64(4);
        assert_eq!(h64.finish(), 4);

        let mut husize = IdentityHasher::default();
        husize.write_usize(5);
        assert_eq!(husize.finish(), 5);

        let mut h_empty = IdentityHasher::default();
        h_empty.write_u64(0);
        assert_eq!(h_empty.finish(), 0);
    }

    #[test]
    fn test_identity_hasher_u64() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u64(u64::MAX);
        assert_eq!(hasher.finish(), u64::MAX);
    }

    #[test]
    fn test_identity_hasher_explicit_u16() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u16(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_explicit_usize() {
        let mut hasher = IdentityHasher::default();
        hasher.write_usize(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_write_fallback_u8() {
        let mut hasher = IdentityHasher::default();
        let bytes = 123u8.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), 123);
    }

    #[test]
    fn test_identity_hasher_write_fallback_u16() {
        let mut hasher = IdentityHasher::default();
        let bytes = 12345u16.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), 12345);
    }

    #[test]
    fn test_identity_hasher_write_fallback_u32() {
        let mut hasher = IdentityHasher::default();
        let bytes = 12345u32.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), 12345);
    }

    #[test]
    fn test_identity_hasher_write_fallback_u64() {
        let mut hasher = IdentityHasher::default();
        let val = 0x1234567890ABCDEFu64;
        let bytes = val.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), val);
    }

    #[test]
    fn test_identity_hasher_write_fallback_u128() {
        let mut hasher = IdentityHasher::default();
        // u128: 0xAAAA... ^ 0x5555...
        // Low: 0x5555555555555555
        // High: 0xAAAAAAAAAAAAAAAA
        let low = 0x5555555555555555u64;
        let high = 0xAAAAAAAAAAAAAAAAu64;
        let val = (high as u128) << 64 | (low as u128);

        let bytes = val.to_le_bytes();
        hasher.write(&bytes);

        assert_eq!(hasher.finish(), low ^ high);
    }

    #[test]
    fn test_identity_hasher_fallback_strings() {
        // Test that different strings produce different hashes (no collision)
        let mut h1 = IdentityHasher::default();
        h1.write(b"foo");

        let mut h2 = IdentityHasher::default();
        h2.write(b"bar");

        assert_ne!(h1.finish(), h2.finish());

        // Ensure not just length
        let mut h3 = IdentityHasher::default();
        h3.write(b"123"); // len 3

        // "foo" and "123" are len 3, but should hash differently
        assert_ne!(h1.finish(), h3.finish());
    }

    #[test]
    fn test_string_hashing_no_marker_collision() {
        // This test replicates how Rust's Hash trait works for str:
        // it calls write(bytes) then write_u8(0xff).
        // Previous implementation of write_u8 overwrote the hash, causing all strings to hash to 255.

        let s1 = "hello";
        let s2 = "world";

        let mut h1 = IdentityHasher::default();
        s1.hash(&mut h1); // Uses standard Hash impl for str

        let mut h2 = IdentityHasher::default();
        s2.hash(&mut h2);

        assert_ne!(
            h1.finish(),
            h2.finish(),
            "Different strings must produce different hashes"
        );
        assert_ne!(
            h1.finish(),
            255,
            "String hash should not collapse to the 0xff marker"
        );
    }

    #[test]
    fn test_identity_hasher_update_state_mutants() {
        let mut hasher = IdentityHasher::default();

        // Test first branch (self.0 == 0)
        hasher.update_state(42);
        assert_eq!(hasher.finish(), 42);

        // Test else branch (self.0 != 0)
        hasher.update_state(10);
        let expected = 42u64 ^ 10u64;
        let expected = expected.wrapping_mul(FNV_PRIME);
        assert_eq!(hasher.finish(), expected);
    }

    #[test]
    fn test_identity_hasher_write_len_1() {
        let mut hasher = IdentityHasher::default();
        hasher.write(&[42u8]);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_write_len_2() {
        let mut hasher = IdentityHasher::default();
        let bytes = 12345u16.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), 12345);
    }

    #[test]
    fn test_identity_hasher_write_len_4() {
        let mut hasher = IdentityHasher::default();
        let bytes = 123456789u32.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), 123456789);
    }

    #[test]
    fn test_identity_hasher_write_len_8() {
        let mut hasher = IdentityHasher::default();
        let bytes = 123456789012345u64.to_le_bytes();
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), 123456789012345);
    }

    #[test]
    fn test_identity_hasher_write_len_16() {
        let mut hasher = IdentityHasher::default();
        let low = 0x1111111111111111u64;
        let high = 0x2222222222222222u64;
        let mut bytes = [0u8; 16];
        bytes[0..8].copy_from_slice(&low.to_le_bytes());
        bytes[8..16].copy_from_slice(&high.to_le_bytes());
        hasher.write(&bytes);
        assert_eq!(hasher.finish(), low ^ high);
    }

    /// A reference FNV-1a implementation for comparison in tests.
    fn reference_fnv1a(bytes: &[u8], initial_state: u64) -> u64 {
        let mut hash = initial_state;
        for &byte in bytes {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(FNV_PRIME);
        }
        hash
    }

    #[test]
    fn test_identity_hasher_write_fallback_fnv() {
        let mut hasher = IdentityHasher::default();
        // length 3 falls into the _ arm
        let bytes = [1u8, 2u8, 3u8];
        hasher.write(&bytes);

        let expected = reference_fnv1a(&bytes, FNV_OFFSET_BASIS);

        assert_eq!(hasher.finish(), expected);
    }

    #[test]
    fn test_identity_hasher_write_fallback_fnv_dirty() {
        let mut hasher = IdentityHasher::default();
        hasher.update_state(42); // make it dirty

        let bytes = [1u8, 2u8, 3u8];
        hasher.write(&bytes);

        let expected = reference_fnv1a(&bytes, 42u64);

        assert_eq!(hasher.finish(), expected);
    }

    #[test]
    fn test_identity_hasher_write_u8() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u8(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_write_u16() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u16(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_write_u32() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u32(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_write_u64() {
        let mut hasher = IdentityHasher::default();
        hasher.write_u64(42);
        assert_eq!(hasher.finish(), 42);
    }

    #[test]
    fn test_identity_hasher_write_usize() {
        let mut hasher = IdentityHasher::default();
        hasher.write_usize(42);
        assert_eq!(hasher.finish(), 42);
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    /// A reference FNV-1a implementation for comparison.
    fn reference_fnv1a(bytes: &[u8]) -> u64 {
        let mut hash = FNV_OFFSET_BASIS;
        for &byte in bytes {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(FNV_PRIME);
        }
        hash
    }

    proptest! {
        /// Property: IdentityHasher's fallback logic for arbitrary byte slices exactly matches a
        /// standard FNV-1a implementation when starting from an empty (0) state.
        ///
        /// This verifies the `_ =>` arm in `IdentityHasher::write`.
        #[test]
        fn prop_identity_hasher_fallback_matches_fnv1a(
            bytes in prop::collection::vec(any::<u8>(), 0..100)
        ) {
            // IdentityHasher's fast paths trigger on exact lengths: 1, 2, 4, 8, 16.
            // When testing the FNV fallback, we ignore these fast-path lengths.
            let is_fast_path = matches!(bytes.len(), 1 | 2 | 4 | 8 | 16);
            if !is_fast_path {
                let mut hasher = IdentityHasher::default();
                hasher.write(&bytes);
                let actual = hasher.finish();

                let expected = if bytes.is_empty() {
                    FNV_OFFSET_BASIS // If bytes is empty but we hit `_ =>`, we do `self.0 = FNV_OFFSET_BASIS` and return.
                } else {
                    reference_fnv1a(&bytes)
                };

                prop_assert_eq!(
                    actual,
                    expected,
                    "IdentityHasher FNV fallback failed for length {}",
                    bytes.len()
                );
            }
        }

        /// Property: IdentityHasher chains FNV-1a correctly if the state is already dirty.
        #[test]
        fn prop_identity_hasher_fallback_chained(
            bytes in prop::collection::vec(any::<u8>(), 1..100)
        ) {
            let is_fast_path = matches!(bytes.len(), 1 | 2 | 4 | 8 | 16);
            if !is_fast_path {
                let mut hasher = IdentityHasher::default();
                // Dirty the state
                hasher.write_u32(42);

                // Fallback will now chain onto this dirty state
                hasher.write(&bytes);
                let actual = hasher.finish();

                let mut expected_state = 42u64;
                for &byte in bytes.iter() {
                    expected_state ^= byte as u64;
                    expected_state = expected_state.wrapping_mul(FNV_PRIME);
                }

                prop_assert_eq!(actual, expected_state);
            }
        }
    }
}

#[cfg(test)]
mod sentinel_identity_hasher_tests {
    use super::*;
    use std::hash::Hasher;

    #[test]
    fn test_identity_hasher_update_state_bitwise_exhaustive() {
        let mut hasher = IdentityHasher::default();

        // Initial state is 0. Writing 0b1010 overwrites the state.
        // If `self.0 == 0` was mutated to `self.0 != 0`, it would try to XOR 0 and multiply by FNV_PRIME.
        // 0 ^ 0b1010 = 0b1010. 0b1010 * FNV_PRIME != 0b1010.
        hasher.update_state(0b1010);
        assert_eq!(hasher.finish(), 0b1010);

        // Now state is 0b1010. Writing 0b0101.
        // XOR: 0b1010 ^ 0b0101 = 0b1111 = 15
        // OR:  0b1010 | 0b0101 = 0b1111 = 15  (Wait, this doesn't kill OR)
        // AND: 0b1010 & 0b0101 = 0b0000 = 0

        // Let's use 0b1100 and 0b1010
        // XOR: 0b1100 ^ 0b1010 = 0b0110 (6)
        // OR:  0b1100 | 0b1010 = 0b1110 (14)
        // AND: 0b1100 & 0b1010 = 0b1000 (8)

        let mut h2 = IdentityHasher::default();
        h2.update_state(0b1100);
        assert_eq!(h2.finish(), 0b1100);

        h2.update_state(0b1010);

        let expected_xor = 0b0110u64.wrapping_mul(FNV_PRIME);
        let expected_or = 0b1110u64.wrapping_mul(FNV_PRIME);
        let expected_and = 0b1000u64.wrapping_mul(FNV_PRIME);

        assert_eq!(h2.finish(), expected_xor);
        assert_ne!(h2.finish(), expected_or);
        assert_ne!(h2.finish(), expected_and);
    }

    #[test]
    fn test_identity_hasher_write_empty_body_exhaustive() {
        let mut h = IdentityHasher::default();
        // If `write_u8` is empty, finish() is 0
        h.write_u8(42);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);

        let mut h = IdentityHasher::default();
        h.write_u16(42);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);

        let mut h = IdentityHasher::default();
        h.write_u32(42);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);

        let mut h = IdentityHasher::default();
        h.write_u64(42);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);

        let mut h = IdentityHasher::default();
        h.write_usize(42);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);

        // If `write` is empty, finish() is 0
        let mut h = IdentityHasher::default();
        h.write(&[42]);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);
    }

    #[test]
    fn test_identity_hasher_write_match_arms_exhaustive() {
        // We want to prove the fast path match arms (1, 2, 4, 8, 16) are taken.
        // If they are deleted, the code falls back to the `_ =>` FNV loop.
        // For length 1, write(42) fast path gives 42. FNV loop gives FNV_OFFSET_BASIS ^ 42 * FNV_PRIME.
        let mut h1 = IdentityHasher::default();
        h1.write(&[42]);
        assert_eq!(h1.finish(), 42); // Fast path
        let mut h1_fnv = IdentityHasher(FNV_OFFSET_BASIS);
        h1_fnv.0 ^= 42;
        h1_fnv.0 = h1_fnv.0.wrapping_mul(FNV_PRIME);
        assert_ne!(h1.finish(), h1_fnv.finish());

        let mut h2 = IdentityHasher::default();
        h2.write(&12345u16.to_le_bytes());
        assert_eq!(h2.finish(), 12345);

        let mut h4 = IdentityHasher::default();
        h4.write(&123456789u32.to_le_bytes());
        assert_eq!(h4.finish(), 123456789);

        let mut h8 = IdentityHasher::default();
        h8.write(&0x1234567890ABCDEFu64.to_le_bytes());
        assert_eq!(h8.finish(), 0x1234567890ABCDEFu64);

        // For length 16, we want to prove `low ^ high` is used, and it's XOR, not OR or AND
        // low: 0b1100, high: 0b1010
        let low = 0b1100u64;
        let high = 0b1010u64;
        let mut h16 = IdentityHasher::default();
        let mut bytes16 = [0u8; 16];
        bytes16[0..8].copy_from_slice(&low.to_le_bytes());
        bytes16[8..16].copy_from_slice(&high.to_le_bytes());
        h16.write(&bytes16);

        let expected_xor = low ^ high;
        let expected_or = low | high;
        let expected_and = low & high;

        assert_eq!(h16.finish(), expected_xor);
        assert_ne!(h16.finish(), expected_or);
        assert_ne!(h16.finish(), expected_and);
    }

    #[test]
    fn test_identity_hasher_write_fallback_bitwise_exhaustive() {
        // Test `if self.0 == 0` mutation to `!=`
        // If it's `!= 0`, it won't set FNV_OFFSET_BASIS, so starting state is 0.
        let mut h = IdentityHasher::default();
        let bytes = [42u8, 43u8, 44u8]; // length 3 hits `_ =>`
        h.write(&bytes);

        let mut expected = FNV_OFFSET_BASIS;
        expected ^= 42;
        expected = expected.wrapping_mul(FNV_PRIME);
        expected ^= 43;
        expected = expected.wrapping_mul(FNV_PRIME);
        expected ^= 44;
        expected = expected.wrapping_mul(FNV_PRIME);

        assert_eq!(h.finish(), expected);

        // Ensure starting from 0 doesn't produce the same result
        let mut wrong_expected = 0u64;
        wrong_expected ^= 42;
        wrong_expected = wrong_expected.wrapping_mul(FNV_PRIME);
        wrong_expected ^= 43;
        wrong_expected = wrong_expected.wrapping_mul(FNV_PRIME);
        wrong_expected ^= 44;
        wrong_expected = wrong_expected.wrapping_mul(FNV_PRIME);
        assert_ne!(h.finish(), wrong_expected);

        // Test loop bitwise mutations `^=` to `|=` or `&=`
        // In the loop, `self.0 ^= *byte as u64;`
        // We need byte to differentiate ^ from | and & with the current state.
        // FNV_OFFSET_BASIS is 0xcbf29ce484222325
        // Let's write `0x25` (the last byte of basis).
        // XOR: 0x...25 ^ 0x25 = 0x...00
        // OR:  0x...25 | 0x25 = 0x...25
        // AND: 0x...25 & 0x25 = 0x...25
        let mut h_bitwise = IdentityHasher::default();
        h_bitwise.write(&[0x25, 0x25, 0x25]);

        let mut expected_xor = FNV_OFFSET_BASIS;
        for &byte in &[0x25, 0x25, 0x25] {
            expected_xor ^= byte as u64;
            expected_xor = expected_xor.wrapping_mul(FNV_PRIME);
        }

        let mut expected_or = FNV_OFFSET_BASIS;
        for &byte in &[0x25, 0x25, 0x25] {
            expected_or |= byte as u64;
            expected_or = expected_or.wrapping_mul(FNV_PRIME);
        }

        let mut expected_and = FNV_OFFSET_BASIS;
        for &byte in &[0x25, 0x25, 0x25] {
            expected_and &= byte as u64;
            expected_and = expected_and.wrapping_mul(FNV_PRIME);
        }

        assert_eq!(h_bitwise.finish(), expected_xor);
        assert_ne!(h_bitwise.finish(), expected_or);
        assert_ne!(h_bitwise.finish(), expected_and);
    }

    #[test]
    fn test_identity_hasher_finish_return_exhaustive() {
        // Kill `replace finish -> u64 with 0` and `1`
        let mut h = IdentityHasher::default();
        h.write_u64(42);
        assert_eq!(h.finish(), 42);
        assert_ne!(h.finish(), 0);
        assert_ne!(h.finish(), 1);
    }
}