simplehash 0.1.3

A simple, fast Rust library implementing common non-cryptographic hash functions: FNV, MurmurHash3, CityHash, and Rendezvous hashing
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
//! # SimpleHash
//!
//! A simple, fast Rust library implementing common non-cryptographic hash functions.
//!
//! ## Overview
//!
//! This library provides implementations of several widely-used non-cryptographic hash functions:
//! - FNV-1 (32-bit and 64-bit variants)
//! - FNV-1a (32-bit and 64-bit variants)
//! - MurmurHash3 (32-bit, 64-bit, and 128-bit variants)
//! - CityHash (64-bit variant)
//! - Rendezvous hashing (Highest Random Weight hashing)
//!
//! Non-cryptographic hash functions are designed for fast computation and good distribution
//! properties, making them suitable for hash tables, checksums, and other general-purpose
//! hashing needs. They are NOT suitable for cryptographic purposes.
//!
//! All hash functions in this library implement the `std::hash::Hasher` trait, making them
//! compatible with Rust's standard collections like `HashMap` and `HashSet`.
//!
//! The CityHash implementation is based on the algorithm developed by Google and available at
//! https://github.com/google/cityhash. CityHash was created by Geoff Pike and Jyrki Alakuijala
//! and is licensed under the MIT License.
//!
//! ### When to use each hash function:
//!
//! - **FNV**: Good for small inputs (< 32 bytes), particularly for integer keys. Simple implementation.
//! - **MurmurHash3**: Excellent general-purpose hash with good distribution across all input sizes.
//! - **CityHash**: Optimized for short strings (< 64 bytes) with excellent performance on modern processors.
//! - **Rendezvous**: For distributed systems when keys need to be consistently mapped to nodes.
//!
//! ### When NOT to use these hash functions:
//!
//! None of the hash functions in this library should be used for:
//! - Cryptographic purposes
//! - Password hashing
//! - Security-sensitive applications
//! - Protection against malicious inputs that could cause collisions
//!
//! ## Example Usage
//!
//! ```rust
//! use simplehash::{fnv1_32, fnv1a_32, fnv1_64, fnv1a_64, murmurhash3_32, murmurhash3_64, murmurhash3_128};
//!
//! let input = "hello world";
//! let bytes = input.as_bytes();
//!
//! // Computing various hashes
//! let fnv1_32_hash = fnv1_32(bytes);
//! let fnv1a_32_hash = fnv1a_32(bytes);
//! let fnv1_64_hash = fnv1_64(bytes);
//! let fnv1a_64_hash = fnv1a_64(bytes);
//! let murmur3_32_hash = murmurhash3_32(bytes, 0);
//! let murmur3_64_hash = murmurhash3_64(bytes, 0);
//! let murmur3_128_hash = murmurhash3_128(bytes, 0);
//!
//! println!("FNV1-32: 0x{:x}", fnv1_32_hash);
//! println!("FNV1a-32: 0x{:x}", fnv1a_32_hash);
//! println!("FNV1-64: 0x{:x}", fnv1_64_hash);
//! println!("FNV1a-64: 0x{:x}", fnv1a_64_hash);
//! println!("MurmurHash3-32: 0x{:x}", murmur3_32_hash);
//! println!("MurmurHash3-64: 0x{:x}", murmur3_64_hash);
//! println!("MurmurHash3-128: 0x{:x}", murmur3_128_hash);
//! ```
//!
//! ## Rendezvous Hashing Example
//!
//! ```rust
//! use simplehash::rendezvous::RendezvousHasher;
//! use std::collections::hash_map::RandomState;
//! use std::hash::BuildHasherDefault;
//! use simplehash::fnv::Fnv1aHasher64;
//!
//! // Create a RendezvousHasher with the standard hasher
//! let std_hasher = RendezvousHasher::<_, RandomState>::new(RandomState::new());
//!
//! // Create a RendezvousHasher with FNV-1a 64-bit hasher
//! let fnv_hasher = RendezvousHasher::<_, BuildHasherDefault<Fnv1aHasher64>>::new(
//!     BuildHasherDefault::<Fnv1aHasher64>::default()
//! );
//!
//! // Define some nodes (servers, cache instances, etc.)
//! let nodes = vec!["server1", "server2", "server3", "server4", "server5"];
//!
//! // Select the preferred node for a key
//! let key = "user_12345";
//! let selected_node = fnv_hasher.select(&key, &nodes).unwrap();
//! println!("Key '{}' is assigned to node '{}'", key, selected_node);
//!
//! // Get the index of the selected node
//! let selected_idx = fnv_hasher.select_index(&key, &nodes).unwrap();
//! println!("Index of selected node: {}", selected_idx);
//!
//! // Get all nodes ranked by preference for this key
//! let ranked_nodes = fnv_hasher.rank(&key, &nodes);
//! println!("Nodes ranked by preference for key '{}':", key);
//! for (i, node) in ranked_nodes.iter().enumerate() {
//!     println!("  {}. {}", i+1, node);
//! }
//! ```
//!
//! ## Choosing a Hash Function
//!
//! - **FNV-1a**: Good general-purpose hash function. Simple to implement with reasonable
//!   performance and distribution properties. The FNV-1a variant is generally preferred
//!   over FNV-1.
//!
//! - **MurmurHash3**: Offers excellent distribution properties and performance, especially
//!   for larger inputs. The 128-bit variant provides better collision resistance.
//!
//! - **CityHash**: Developed by Google specifically for string hashing, with excellent
//!   performance for short to medium-length strings. It's a good choice for hash tables
//!   where the keys are typically strings.
//!
//! - **Rendezvous Hashing**: Not a raw hash function but rather a consistent hashing algorithm
//!   that uses an underlying hash function. It's designed for distributed systems where keys
//!   need to be consistently mapped to servers, with minimal redistribution when servers are
//!   added or removed. This library's implementation works with any hasher implementing the
//!   `std::hash::Hasher` trait.
//!
//! ## Using with HashMap and HashSet
//!
//! All hashers in this library implement the `std::hash::Hasher` trait, making them
//! compatible with standard collections. This allows you to use these faster, non-cryptographic
//! hashers in place of the default SipHash implementation when performance is a priority.
//!
//! ```rust
//! use simplehash::fnv::Fnv1aHasher64;
//! use simplehash::murmur::{MurmurHasher32, MurmurHasher64};
//! use std::collections::{HashMap, HashSet};
//! use std::hash::BuildHasherDefault;
//!
//! // Using FNV-1a with HashMap
//! let mut map: HashMap<String, u32, BuildHasherDefault<Fnv1aHasher64>> =
//!     HashMap::with_hasher(BuildHasherDefault::<Fnv1aHasher64>::default());
//! map.insert("key".to_string(), 42);
//!
//! // Using FNV-1a with HashSet
//! let mut set: HashSet<String, BuildHasherDefault<Fnv1aHasher64>> =
//!     HashSet::with_hasher(BuildHasherDefault::<Fnv1aHasher64>::default());
//! set.insert("value".to_string());
//!
//! // Create a BuildHasher for MurmurHash3 32-bit
//! #[derive(Default, Clone)]
//! struct MurmurHash3_32BuildHasher;
//!
//! impl std::hash::BuildHasher for MurmurHash3_32BuildHasher {
//!     type Hasher = MurmurHasher32;
//!
//!     fn build_hasher(&self) -> Self::Hasher {
//!         MurmurHasher32::new(0) // Using seed 0
//!     }
//! }
//!
//! // Create a BuildHasher for MurmurHash3 64-bit
//! #[derive(Default, Clone)]
//! struct MurmurHash3_64BuildHasher;
//!
//! impl std::hash::BuildHasher for MurmurHash3_64BuildHasher {
//!     type Hasher = MurmurHasher64;
//!
//!     fn build_hasher(&self) -> Self::Hasher {
//!         MurmurHasher64::new(0) // Using seed 0
//!     }
//! }
//!
//! // Using MurmurHash3 32-bit with HashMap
//! let mut murmur32_map: HashMap<String, u32, MurmurHash3_32BuildHasher> =
//!     HashMap::with_hasher(MurmurHash3_32BuildHasher);
//! murmur32_map.insert("key".to_string(), 42);
//!
//! // Using MurmurHash3 64-bit with HashMap
//! let mut murmur64_map: HashMap<String, u32, MurmurHash3_64BuildHasher> =
//!     HashMap::with_hasher(MurmurHash3_64BuildHasher);
//! murmur64_map.insert("key".to_string(), 42);
//! ```
//!
//! ### Performance Characteristics
//!
//! * **FNV-1a**:
//!   - Very fast for small keys (like short strings, integers)
//!   - Uses less memory than SipHash (Rust's default)
//!   - Particularly effective for HashMaps with small keys
//!   - Not recommended for untrusted inputs (e.g., network data) due to lack of DoS protection
//!
//! * **MurmurHash3**:
//!   - Excellent performance for medium to large inputs
//!   - Better distribution properties than FNV
//!   - Good compromise between speed and collision resistance
//!   - The 32-bit version is faster, while the 128-bit version has better collision resistance
//!   - When developers need a 64-bit hash, they can use the 64-bit variant which uses half of the 128-bit output
//!
//! ## Implementation Notes
//!
//! All hash functions in this library:
//! - Accept a byte slice (`&[u8]`) as input
//! - Return an unsigned integer of the appropriate size
//! - Are deterministic (same input always produces same output)
//! - Are endian-agnostic (produce same result regardless of platform endianness)
//!
//! The MurmurHash3 implementations are compatible with reference implementations
//! in other languages (Python's mmh3 package and the original C++ implementation).

use std::hash::Hasher;

pub mod city;
pub mod fnv;
pub mod murmur;
pub mod rendezvous;

// Re-export for users to use directly
pub use city::*;
pub use fnv::*;
pub use murmur::*;
pub use rendezvous::*;

/// Computes the FNV-1 hash (32-bit) of the provided data.
///
/// This is the original FNV-1 algorithm developed by Glenn Fowler, Landon Curt Noll,
/// and Phong Vo. For most purposes, you should prefer [`fnv1a_32`] instead, which
/// generally has better dispersion properties.
///
/// # Algorithm
///
/// FNV-1 works by:
/// 1. Starting with an initial basis value (2166136261 for 32-bit FNV-1)
/// 2. For each byte in the input:
///    a. Multiply the current hash by the FNV prime (16777619 for 32-bit)
///    b. XOR the result with the current byte
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
///
/// # Returns
///
/// A 32-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```
/// use simplehash::fnv1_32;
///
/// let data = b"hello world";
/// let hash = fnv1_32(data);
/// println!("FNV1-32 hash: 0x{:08x}", hash);
/// ```
#[inline]
pub fn fnv1_32(data: &[u8]) -> u32 {
    let mut hasher = fnv::FnvHasher32::new();
    hasher.write(data);
    hasher.finish_raw()
}

/// Computes the FNV-1a hash (32-bit) of the provided data.
///
/// FNV-1a is an improved variant of the original FNV-1 algorithm with better
/// dispersion properties. It is generally considered superior to FNV-1 for most use cases.
///
/// # Algorithm
///
/// FNV-1a works by:
/// 1. Starting with an initial basis value (2166136261 for 32-bit FNV-1a)
/// 2. For each byte in the input:
///    a. XOR the current hash with the current byte
///    b. Multiply the result by the FNV prime (16777619 for 32-bit)
///
/// The key difference from FNV-1 is the order of operations (XOR then multiply, vs multiply then XOR).
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
///
/// # Returns
///
/// A 32-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```
/// use simplehash::fnv1a_32;
///
/// let data = b"hello world";
/// let hash = fnv1a_32(data);
/// println!("FNV1a-32 hash: 0x{:08x}", hash);
/// ```
#[inline]
pub fn fnv1a_32(data: &[u8]) -> u32 {
    let mut hasher = fnv::Fnv1aHasher32::new();
    hasher.write(data);
    hasher.finish_raw()
}

/// Computes the FNV-1 hash (64-bit) of the provided data.
///
/// This is the 64-bit variant of the original FNV-1 algorithm, offering a larger
/// hash space and reduced collision probability compared to the 32-bit version.
/// For most purposes, the [`fnv1a_64`] variant is preferred for its better dispersion properties.
///
/// # Algorithm
///
/// FNV-1 (64-bit) works by:
/// 1. Starting with an initial basis value (14695981039346656037 for 64-bit FNV-1)
/// 2. For each byte in the input:
///    a. Multiply the current hash by the FNV prime (1099511628211 for 64-bit)
///    b. XOR the result with the current byte
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
///
/// # Returns
///
/// A 64-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```
/// use simplehash::fnv1_64;
///
/// let data = b"hello world";
/// let hash = fnv1_64(data);
/// println!("FNV1-64 hash: 0x{:016x}", hash);
/// ```
#[inline]
pub fn fnv1_64(data: &[u8]) -> u64 {
    let mut hasher = fnv::FnvHasher64::new();
    hasher.write(data);
    hasher.finish_raw()
}

/// Computes the FNV-1a hash (64-bit) of the provided data.
///
/// FNV-1a (64-bit) is an improved variant of the original FNV-1 algorithm with better
/// dispersion properties and a larger hash space than the 32-bit variant. It is generally
/// preferred over FNV-1 (64-bit) for most applications.
///
/// # Algorithm
///
/// FNV-1a (64-bit) works by:
/// 1. Starting with an initial basis value (14695981039346656037 for 64-bit FNV-1a)
/// 2. For each byte in the input:
///    a. XOR the current hash with the current byte
///    b. Multiply the result by the FNV prime (1099511628211 for 64-bit)
///
/// The key difference from FNV-1 is the order of operations (XOR then multiply, vs multiply then XOR).
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
///
/// # Returns
///
/// A 64-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```
/// use simplehash::fnv1a_64;
///
/// let data = b"hello world";
/// let hash = fnv1a_64(data);
/// println!("FNV1a-64 hash: 0x{:016x}", hash);
/// ```
#[inline]
pub fn fnv1a_64(data: &[u8]) -> u64 {
    let mut hasher = fnv::Fnv1aHasher64::new();
    hasher.write(data);
    hasher.finish_raw()
}

/// Computes the MurmurHash3 32-bit hash of the provided data.
///
/// MurmurHash3 is a non-cryptographic hash function created by Austin Appleby in 2008.
/// This 32-bit implementation is optimized for x86 architectures and provides excellent
/// distribution, avalanche behavior, and performance characteristics.
///
/// # Algorithm
///
/// MurmurHash3 (32-bit) works by:
/// 1. Processing the input in 4-byte (32-bit) blocks
/// 2. Applying carefully chosen magic constants and bit manipulation operations
/// 3. Processing any remaining bytes (the "tail")
/// 4. Finalizing the hash with additional mixing to improve avalanche behavior
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
/// * `seed` - A 32-bit seed value that can be used to create different hash values for the same input
///
/// # Returns
///
/// A 32-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```
/// use simplehash::murmurhash3_32;
///
/// let data = b"hello world";
/// let hash = murmurhash3_32(data, 0);  // Using seed value 0
/// println!("MurmurHash3-32 hash: 0x{:08x}", hash);
///
/// // Using a different seed produces a different hash
/// let hash2 = murmurhash3_32(data, 42);
/// println!("MurmurHash3-32 hash (seed 42): 0x{:08x}", hash2);
/// ```
///
/// # Compatibility
///
/// This implementation is compatible with other MurmurHash3 implementations including the
/// original C++ implementation by Austin Appleby and the Python mmh3 package.
#[inline]
pub fn murmurhash3_32(data: &[u8], seed: u32) -> u32 {
    let mut hasher = murmur::MurmurHasher32::new(seed);
    hasher.write(data);
    hasher.finish_u32()
}

/// Computes the MurmurHash3 64-bit hash of the provided data.
///
/// This is implemented by using the lower 64 bits of the 128-bit MurmurHash3 algorithm.
/// When developers need a 64-bit hash, they can simply use half of the 128-bit variant,
/// which provides good performance and distribution properties while producing a 64-bit result.
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
/// * `seed` - A 32-bit seed value that can be used to create different hash values for the same input
///
/// # Returns
///
/// A 64-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```rust
/// use simplehash::murmurhash3_64;
///
/// let data = b"hello world";
/// let hash = murmurhash3_64(data, 0);  // Using seed value 0
/// println!("MurmurHash3-64 hash: 0x{:016x}", hash);
///
/// // Using a different seed produces a different hash
/// let hash2 = murmurhash3_64(data, 42);
/// println!("MurmurHash3-64 hash (seed 42): 0x{:016x}", hash2);
/// ```
///
/// # Compatibility
///
/// This implementation is compatible with other MurmurHash3 64-bit implementations.
/// The value returned matches the lower 64 bits returned by mmh3.hash64() in Python.
#[inline]
pub fn murmurhash3_64(data: &[u8], seed: u32) -> u64 {
    let mut hasher = murmur::MurmurHasher64::new(seed);
    hasher.write(data);
    hasher.finish_u64()
}

/// Computes the MurmurHash3 128-bit hash of the provided data.
///
/// MurmurHash3 is a non-cryptographic hash function created by Austin Appleby in 2008.
/// This 128-bit implementation provides superior collision resistance compared to the 32-bit
/// variant, making it suitable for applications requiring a larger hash space.
///
/// # Algorithm
///
/// MurmurHash3 (128-bit) works by:
/// 1. Processing the input in 16-byte (128-bit) blocks
/// 2. Using four 32-bit state variables (h1, h2, h3, h4) that are updated as data is processed
/// 3. Applying carefully chosen magic constants and bit manipulation operations
/// 4. Processing any remaining bytes (the "tail")
/// 5. Finalizing the hash with additional mixing to improve avalanche behavior
///
/// # Parameters
///
/// * `data` - A slice of bytes to hash
/// * `seed` - A 32-bit seed value that can be used to create different hash values for the same input
///
/// # Returns
///
/// A 128-bit unsigned integer representing the hash value
///
/// # Example
///
/// ```
/// use simplehash::murmurhash3_128;
///
/// let data = b"hello world";
/// let hash = murmurhash3_128(data, 0);  // Using seed value 0
/// println!("MurmurHash3-128 hash: 0x{:032x}", hash);
///
/// // Using a different seed produces a different hash
/// let hash2 = murmurhash3_128(data, 42);
/// println!("MurmurHash3-128 hash (seed 42): 0x{:032x}", hash2);
/// ```
///
/// # Compatibility
///
/// This implementation is compatible with other MurmurHash3 128-bit implementations including the
/// original C++ implementation by Austin Appleby and the Python mmh3 package.
///
/// Note that the lower 64 bits of the result match the value returned by mmh3.hash64() in Python.
#[inline]
pub fn murmurhash3_128(data: &[u8], seed: u32) -> u128 {
    let mut hasher = murmur::MurmurHasher128::new(seed);
    hasher.write(data);
    hasher.finish_u128()
}

// Test corpus for validation against Python mmh3 implementation
#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, from_str};
    use std::fs::File;
    use std::io::Read;

    #[test]
    fn test_fnv1_32() {
        let data1 = b"hello";
        // Get the result from our implementation
        let result = fnv1_32(data1);
        // Debug print the result
        println!("FNV1-32 for 'hello': 0x{:x} ({})", result, result);
    }

    #[test]
    fn test_fnv1a_32() {
        let data1 = b"hello";
        // Get the result from our implementation
        let result = fnv1a_32(data1);
        // Debug print the result
        println!("FNV1a-32 for 'hello': 0x{:x} ({})", result, result);
    }

    #[test]
    fn test_fnv1_64() {
        let data1 = b"hello";
        // Get the result from our implementation
        let result = fnv1_64(data1);
        // Debug print the result
        println!("FNV1-64 for 'hello': 0x{:x} ({})", result, result);
    }

    #[test]
    fn test_fnv1a_64() {
        let data1 = b"hello";
        // Get the result from our implementation
        let result = fnv1a_64(data1);
        // Debug print the result
        println!("FNV1a-64 for 'hello': 0x{:x} ({})", result, result);
    }

    #[test]
    fn test_murmurhash3_32() {
        // Test cases with debug output
        let data1 = b"hello";
        let result = murmurhash3_32(data1, 0);
        println!(
            "MurmurHash3-32 for 'hello' (seed 0): 0x{:x} ({})",
            result, result
        );

        let data2 = b"hello world";
        let result2 = murmurhash3_32(data2, 0);
        println!(
            "MurmurHash3-32 for 'hello world' (seed 0): 0x{:x} ({})",
            result2, result2
        );

        let data3 = b"";
        let result3 = murmurhash3_32(data3, 0);
        println!(
            "MurmurHash3-32 for '' (seed 0): 0x{:x} ({})",
            result3, result3
        );

        let data4 = b"aaaa";
        let result4 = murmurhash3_32(data4, 0x9747b28c);
        println!(
            "MurmurHash3-32 for 'aaaa' (seed 0x9747b28c): 0x{:x} ({})",
            result4, result4
        );
    }

    #[test]
    fn test_murmurhash3_64() {
        // Test with debug output
        let data = b"hello world";
        let result = murmurhash3_64(data, 0);
        println!(
            "MurmurHash3-64 for 'hello world' (seed 0): 0x{:x} ({})",
            result, result
        );

        let empty = b"";
        let result_empty = murmurhash3_64(empty, 0);
        println!(
            "MurmurHash3-64 for '' (seed 0): 0x{:x} ({})",
            result_empty, result_empty
        );

        // Verify that the 64-bit result matches the lower 64 bits of 128-bit variant
        let result_128 = murmurhash3_128(data, 0);
        let result_128_lower64 = result_128 as u64;
        assert_eq!(
            result, result_128_lower64,
            "64-bit result should match lower 64 bits of 128-bit result"
        );
    }

    #[test]
    fn test_murmurhash3_128() {
        // Test with debug output
        let data = b"hello world";
        let result = murmurhash3_128(data, 0);
        println!(
            "MurmurHash3-128 for 'hello world' (seed 0): 0x{:x} ({})",
            result, result
        );

        let empty = b"";
        let result_empty = murmurhash3_128(empty, 0);
        println!(
            "MurmurHash3-128 for '' (seed 0): 0x{:x} ({})",
            result_empty, result_empty
        );
    }

    #[test]
    fn test_against_mmh3_python() {
        // Read the test corpus generated by Python
        let mut file = match File::open("data/mmh3_test_corpus.json") {
            Ok(file) => file,
            Err(_) => {
                println!("Skipping Python mmh3 comparison test - mmh3_test_corpus.json not found");
                return;
            }
        };

        let mut contents = String::new();
        file.read_to_string(&mut contents).unwrap();

        let corpus: Value = from_str(&contents).unwrap();

        // Test each entry in the corpus
        if let Value::Array(entries) = corpus {
            for entry in entries {
                // Get the input bytes
                let input_bytes = entry["input_bytes"]
                    .as_array()
                    .expect("Expected input_bytes to be an array");
                let bytes: Vec<u8> = input_bytes
                    .iter()
                    .map(|v| v.as_u64().expect("Expected input_byte to be a number") as u8)
                    .collect();

                // Get the input string for error messages
                let input_str = entry["input"].as_str().unwrap_or("binary data");

                // Test MurmurHash3 32-bit with seed 0
                if let Some(py_result_32_0) = entry["murmur3_32_seed0"].as_u64() {
                    let rust_result_32_0 = murmurhash3_32(&bytes, 0);

                    println!(
                        "Testing 32-bit seed 0 for input: '{}' - Python: {} vs Rust: {}",
                        input_str, py_result_32_0, rust_result_32_0
                    );

                    assert_eq!(
                        rust_result_32_0, py_result_32_0 as u32,
                        "32-bit seed 0 mismatch for input: '{}'",
                        input_str
                    );
                }

                // Test MurmurHash3 32-bit with seed 42
                if let Some(py_result_32_42) = entry["murmur3_32_seed42"].as_u64() {
                    let rust_result_32_42 = murmurhash3_32(&bytes, 42);

                    println!(
                        "Testing 32-bit seed 42 for input: '{}' - Python: {} vs Rust: {}",
                        input_str, py_result_32_42, rust_result_32_42
                    );

                    assert_eq!(
                        rust_result_32_42, py_result_32_42 as u32,
                        "32-bit seed 42 mismatch for input: '{}'",
                        input_str
                    );
                }

                // Test MurmurHash3 128-bit with seed 0 (just compare lower 64 bits)
                if let Some(py_result_128_0) = entry["murmur3_128_seed0"].as_u64() {
                    let rust_result_128_0 = murmurhash3_128(&bytes, 0);
                    let rust_low64_0 = rust_result_128_0 as u64;

                    println!(
                        "Testing 128-bit seed 0 (low 64 bits) for input: '{}' - Python: {} vs Rust: {}",
                        input_str, py_result_128_0, rust_low64_0
                    );

                    assert_eq!(
                        rust_low64_0, py_result_128_0,
                        "128-bit seed 0 (low 64 bits) mismatch for input: '{}'",
                        input_str
                    );
                }

                // Test MurmurHash3 128-bit with seed 42
                if let Some(py_result_128_42) = entry["murmur3_128_seed42"].as_u64() {
                    let rust_result_128_42 = murmurhash3_128(&bytes, 42);
                    let rust_low64_42 = rust_result_128_42 as u64;

                    println!(
                        "Testing 128-bit seed 42 (low 64 bits) for input: '{}' - Python: {} vs Rust: {}",
                        input_str, py_result_128_42, rust_low64_42
                    );

                    assert_eq!(
                        rust_low64_42, py_result_128_42,
                        "128-bit seed 42 (low 64 bits) mismatch for input: '{}'",
                        input_str
                    );
                }
            }
        }
    }

    #[test]
    fn test_against_go_fnv() {
        // Read the test corpus generated by Go
        let mut file = match File::open("data/fnv_test_corpus.json") {
            Ok(file) => file,
            Err(_) => {
                println!("Skipping Go FNV comparison test - fnv_test_corpus.json not found");
                println!("Run 'go run generate_fnv_corpus.go' to generate the test corpus first");
                return;
            }
        };

        let mut contents = String::new();
        file.read_to_string(&mut contents).unwrap();

        let corpus: Value = match from_str(&contents) {
            Ok(v) => v,
            Err(e) => {
                println!("Error parsing JSON: {}", e);
                return;
            }
        };

        let mut total_tests = 0;
        let mut passed_tests = 0;

        // Test each entry in the corpus
        if let Value::Array(entries) = corpus {
            for entry in entries {
                // Get the input bytes
                let input_bytes = match entry["input_bytes"].as_array() {
                    Some(arr) => arr,
                    None => {
                        println!("Expected input_bytes to be an array");
                        continue;
                    }
                };

                let bytes: Vec<u8> = match input_bytes
                    .iter()
                    .map(|v| v.as_i64().map(|n| n as u8))
                    .collect::<Option<Vec<u8>>>()
                {
                    Some(b) => b,
                    None => {
                        println!("Expected input_bytes to contain valid byte values");
                        continue;
                    }
                };

                // Get the input string for error messages
                let input_str = entry["input"].as_str().unwrap_or("binary data");

                // Verify FNV1-32
                if let Some(go_fnv1_32) = entry["fnv1_32"].as_u64() {
                    total_tests += 1;
                    let rust_fnv1_32 = fnv1_32(&bytes);

                    println!(
                        "Testing FNV1-32 for input: '{}' - Go: {} vs Rust: {}",
                        input_str, go_fnv1_32, rust_fnv1_32
                    );

                    assert_eq!(
                        rust_fnv1_32, go_fnv1_32 as u32,
                        "FNV1-32 mismatch for input: '{}'",
                        input_str
                    );
                    passed_tests += 1;
                }

                // Verify FNV1a-32
                if let Some(go_fnv1a_32) = entry["fnv1a_32"].as_u64() {
                    total_tests += 1;
                    let rust_fnv1a_32 = fnv1a_32(&bytes);

                    println!(
                        "Testing FNV1a-32 for input: '{}' - Go: {} vs Rust: {}",
                        input_str, go_fnv1a_32, rust_fnv1a_32
                    );

                    assert_eq!(
                        rust_fnv1a_32, go_fnv1a_32 as u32,
                        "FNV1a-32 mismatch for input: '{}'",
                        input_str
                    );
                    passed_tests += 1;
                }

                // Verify FNV1-64
                if let Some(go_fnv1_64) = entry["fnv1_64"].as_u64() {
                    total_tests += 1;
                    let rust_fnv1_64 = fnv1_64(&bytes);

                    println!(
                        "Testing FNV1-64 for input: '{}' - Go: {} vs Rust: {}",
                        input_str, go_fnv1_64, rust_fnv1_64
                    );

                    assert_eq!(
                        rust_fnv1_64, go_fnv1_64,
                        "FNV1-64 mismatch for input: '{}'",
                        input_str
                    );
                    passed_tests += 1;
                }

                // Verify FNV1a-64
                if let Some(go_fnv1a_64) = entry["fnv1a_64"].as_u64() {
                    total_tests += 1;
                    let rust_fnv1a_64 = fnv1a_64(&bytes);

                    println!(
                        "Testing FNV1a-64 for input: '{}' - Go: {} vs Rust: {}",
                        input_str, go_fnv1a_64, rust_fnv1a_64
                    );

                    assert_eq!(
                        rust_fnv1a_64, go_fnv1a_64,
                        "FNV1a-64 mismatch for input: '{}'",
                        input_str
                    );
                    passed_tests += 1;
                }
            }
        }

        // Print summary
        println!("FNV Verification Summary:");
        println!(
            "Passed {}/{} tests ({}%)",
            passed_tests,
            total_tests,
            if total_tests > 0 {
                passed_tests * 100 / total_tests
            } else {
                0
            }
        );
    }
}