zipora 4.1.0

High-performance Rust implementation providing advanced data structures and compression algorithms with memory safety guarantees. Features LRU page cache, sophisticated caching layer, fiber-based concurrency, real-time compression, secure memory pools, SIMD optimizations, and complete C FFI for migration from C++.
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
use super::*;
use std::hash::{BuildHasher, Hasher};

// --- Custom hasher that returns a fixed u64, for testing sentinel edge cases ---

#[derive(Clone)]
struct FixedHashBuilder(u64);

impl BuildHasher for FixedHashBuilder {
    type Hasher = FixedHasher;
    fn build_hasher(&self) -> FixedHasher {
        FixedHasher(self.0)
    }
}

struct FixedHasher(u64);

impl Hasher for FixedHasher {
    fn finish(&self) -> u64 {
        self.0
    }
    fn write(&mut self, _bytes: &[u8]) {}
}

// ==================== Config creation tests ====================

#[test]
fn test_unified_hash_map_creation() {
    let map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    assert_eq!(map.len(), 0);
    assert!(map.is_empty());
}

#[test]
fn test_cache_optimized_config() {
    let result = ZiporaHashMap::<String, i32>::with_config(ZiporaHashMapConfig::cache_optimized());
    assert!(
        result.is_err(),
        "CacheOptimized strategy should be rejected at construction"
    );
}

#[test]
fn test_string_optimized_config() {
    let result = ZiporaHashMap::<String, i32>::with_config(ZiporaHashMapConfig::string_optimized());
    assert!(
        result.is_err(),
        "StringOptimized strategy should be rejected at construction"
    );
}

#[test]
fn test_small_inline_config() {
    let mut map: ZiporaHashMap<i32, String> =
        ZiporaHashMap::with_config(ZiporaHashMapConfig::small_inline(4)).expect("invariant broken");
    assert_eq!(map.len(), 0);

    // Fill up to inline capacity
    for i in 0..16 {
        map.insert(i, i.to_string()).expect("invariant broken");
    }
    assert_eq!(map.len(), 16);

    // Verify all entries
    for i in 0..16 {
        assert_eq!(map.get(&i), Some(&i.to_string()));
    }
}

// ==================== Core operations ====================

#[test]
fn test_insert_and_get() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    assert_eq!(
        map.insert("hello".to_string(), 42)
            .expect("invariant broken"),
        None
    );
    assert_eq!(map.get("hello"), Some(&42));
    assert_eq!(map.len(), 1);
    assert!(!map.is_empty());
}

#[test]
fn test_insert_overwrite_returns_old_value() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    assert_eq!(
        map.insert("key".to_string(), 1).expect("invariant broken"),
        None
    );
    assert_eq!(
        map.insert("key".to_string(), 2).expect("invariant broken"),
        Some(1)
    );
    assert_eq!(map.get("key"), Some(&2));
    assert_eq!(map.len(), 1);
}

#[test]
fn test_get_nonexistent() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("a".to_string(), 1).expect("invariant broken");
    assert_eq!(map.get("b"), None);
    assert_eq!(map.get(""), None);
}

#[test]
fn test_remove_existing() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("key".to_string(), 99).expect("invariant broken");
    assert_eq!(map.remove("key"), Some(99));
    assert_eq!(map.get("key"), None);
    assert_eq!(map.len(), 0);
}

#[test]
fn test_remove_nonexistent() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("a".to_string(), 1).expect("invariant broken");
    assert_eq!(map.remove("b"), None);
    assert_eq!(map.len(), 1);
}

#[test]
fn test_get_mut() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("key".to_string(), 10).expect("invariant broken");
    if let Some(val) = map.get_mut("key") {
        *val = 20;
    }
    assert_eq!(map.get("key"), Some(&20));
}

#[test]
fn test_get_mut_nonexistent() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    assert!(map.get_mut("nope").is_none());
}

#[test]
fn test_contains_key() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("yes".to_string(), 1).expect("invariant broken");
    assert!(map.contains_key("yes"));
    assert!(!map.contains_key("no"));
}

#[test]
fn test_len_tracking() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    assert_eq!(map.len(), 0);

    map.insert(1, 10).expect("invariant broken");
    assert_eq!(map.len(), 1);

    map.insert(2, 20).expect("invariant broken");
    assert_eq!(map.len(), 2);

    // Overwrite doesn't increase len
    map.insert(1, 11).expect("invariant broken");
    assert_eq!(map.len(), 2);

    map.remove(&1);
    assert_eq!(map.len(), 1);

    map.remove(&2);
    assert_eq!(map.len(), 0);
    assert!(map.is_empty());
}

#[test]
fn test_single_element() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert(42, 100).expect("invariant broken");
    assert_eq!(map.get(&42), Some(&100));
    assert_eq!(map.len(), 1);
    assert_eq!(map.remove(&42), Some(100));
    assert!(map.is_empty());
}

// ==================== Resize / rehash ====================

#[test]
fn test_resize_preserves_all_entries() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    let n = 200;
    for i in 0..n {
        map.insert(i, i * 10).expect("invariant broken");
    }
    assert_eq!(map.len(), n as usize);
    for i in 0..n {
        assert_eq!(
            map.get(&i),
            Some(&(i * 10)),
            "key {} missing after resize",
            i
        );
    }
}

#[test]
fn test_resize_compacts_tombstones() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    // Fill to just under resize threshold
    for i in 0..15 {
        map.insert(i, i).expect("invariant broken");
    }
    // Remove half to create tombstones
    for i in 0..8 {
        map.remove(&i);
    }
    // The 7 remaining entries should still be accessible
    for i in 8..15 {
        assert_eq!(map.get(&i), Some(&i));
    }
    // Insert enough to force resize — tombstones should be compacted
    for i in 100..120 {
        map.insert(i, i).expect("invariant broken");
    }
    // All surviving entries must be present
    for i in 8..15 {
        assert_eq!(map.get(&i), Some(&i), "key {} lost after resize", i);
    }
    for i in 100..120 {
        assert_eq!(map.get(&i), Some(&i), "key {} lost after resize", i);
    }
    // Removed entries must stay gone
    for i in 0..8 {
        assert_eq!(map.get(&i), None, "removed key {} reappeared", i);
    }
}

// ==================== Tombstone behavior ====================

#[test]
fn test_tombstone_get_returns_none() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("gone".to_string(), 1).expect("invariant broken");
    map.remove("gone");
    assert_eq!(map.get("gone"), None);
}

#[test]
fn test_tombstone_slot_reuse_same_key() {
    let mut map: ZiporaHashMap<String, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("reuse".to_string(), 1)
        .expect("invariant broken");
    map.remove("reuse");
    // Re-inserting same key should work (tombstone slot eligible)
    assert_eq!(
        map.insert("reuse".to_string(), 2)
            .expect("invariant broken"),
        None
    );
    assert_eq!(map.get("reuse"), Some(&2));
}

#[test]
fn test_tombstone_does_not_break_probe_chain() {
    // Use a fixed hasher so all keys hash to the same value,
    // guaranteeing a linear probe chain: slot 1, 2, 3, ...
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(42))
            .expect("invariant broken");

    // All three keys hash to 42 → same initial slot → probe chain
    map.insert(1, 10).expect("invariant broken");
    map.insert(2, 20).expect("invariant broken");
    map.insert(3, 30).expect("invariant broken");

    // Remove the middle of the chain
    assert_eq!(map.remove(&2), Some(20));

    // Key before tombstone
    assert_eq!(map.get(&1), Some(&10));
    // Key after tombstone — probe must skip the tombstone
    assert_eq!(map.get(&3), Some(&30));
    // Removed key
    assert_eq!(map.get(&2), None);
}

#[test]
fn test_multiple_tombstones_in_chain() {
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(7))
            .expect("invariant broken");

    for i in 0..6 {
        map.insert(i, i * 100).expect("invariant broken");
    }
    // Remove alternating: 0, 2, 4
    map.remove(&0);
    map.remove(&2);
    map.remove(&4);

    assert_eq!(map.get(&1), Some(&100));
    assert_eq!(map.get(&3), Some(&300));
    assert_eq!(map.get(&5), Some(&500));
    assert_eq!(map.get(&0), None);
    assert_eq!(map.get(&2), None);
    assert_eq!(map.get(&4), None);
    assert_eq!(map.len(), 3);
}

// ==================== Hash sentinel collision fix ====================

#[test]
fn test_hash_sentinel_zero() {
    // All keys hash to raw 0 → sanitized to 1
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(0))
            .expect("invariant broken");

    map.insert(10, 100).expect("invariant broken");
    map.insert(20, 200).expect("invariant broken");
    assert_eq!(map.get(&10), Some(&100));
    assert_eq!(map.get(&20), Some(&200));
    assert_eq!(map.remove(&10), Some(100));
    assert_eq!(map.get(&10), None);
    assert_eq!(map.get(&20), Some(&200));
    assert_eq!(map.len(), 1);
}

#[test]
fn test_hash_sentinel_max() {
    // All keys hash to raw u64::MAX → sanitized to u64::MAX - 1
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(u64::MAX))
            .expect("invariant broken");

    map.insert(10, 100).expect("invariant broken");
    map.insert(20, 200).expect("invariant broken");
    assert_eq!(map.get(&10), Some(&100));
    assert_eq!(map.get(&20), Some(&200));
    assert_eq!(map.remove(&10), Some(100));
    assert_eq!(map.get(&10), None);
    assert_eq!(map.get(&20), Some(&200));
    assert_eq!(map.len(), 1);
}

#[test]
fn test_hash_sentinel_max_with_get_mut() {
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(u64::MAX))
            .expect("invariant broken");

    map.insert(1, 10).expect("invariant broken");
    if let Some(v) = map.get_mut(&1) {
        *v = 99;
    }
    assert_eq!(map.get(&1), Some(&99));
}

// ==================== Iterator ====================

#[test]
fn test_iterator_basic() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert(1, 10).expect("invariant broken");
    map.insert(2, 20).expect("invariant broken");
    map.insert(3, 30).expect("invariant broken");

    let mut collected: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
    collected.sort();
    assert_eq!(collected, vec![(1, 10), (2, 20), (3, 30)]);
}

#[test]
fn test_iterator_skips_tombstones() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert(1, 10).expect("invariant broken");
    map.insert(2, 20).expect("invariant broken");
    map.insert(3, 30).expect("invariant broken");
    map.remove(&2);

    let mut collected: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
    collected.sort();
    assert_eq!(collected, vec![(1, 10), (3, 30)]);
}

#[test]
fn test_iterator_empty() {
    let map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    assert_eq!(map.iter().count(), 0);
}

#[test]
fn test_iterator_all_removed() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert(1, 10).expect("invariant broken");
    map.insert(2, 20).expect("invariant broken");
    map.remove(&1);
    map.remove(&2);
    assert_eq!(map.iter().count(), 0);
}

// ==================== Backward shift deletion ====================

#[test]
fn test_backward_shift_delete() {
    // Directly exercise the backward_shift_delete method
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(0))
            .expect("invariant broken");

    // Insert 4 keys — all collide, forming a probe chain
    map.insert(1, 10).expect("invariant broken");
    map.insert(2, 20).expect("invariant broken");
    map.insert(3, 30).expect("invariant broken");
    map.insert(4, 40).expect("invariant broken");

    // Manually invoke backward_shift_delete on the first slot
    if let HashMapStorage::Standard { entries, mask, .. } = &mut map.storage {
        // Find the slot containing key 1 (the sanitized hash of 0 is 1 → slot 1 & mask)
        let target_slot = 1usize & *mask;
        entries[target_slot].hash = 0;
        entries[target_slot].key = None;
        entries[target_slot].value = None;
        let m = *mask;
        ZiporaHashMap::<i32, i32, FixedHashBuilder>::backward_shift_delete(entries, m, target_slot);
    }

    // After backward shift: keys 2, 3, 4 should be shifted backward
    // and remain findable (the chain is compacted, no tombstone needed)
    assert_eq!(map.get(&2), Some(&20));
    assert_eq!(map.get(&3), Some(&30));
    assert_eq!(map.get(&4), Some(&40));
}

// ==================== Clear ====================

#[test]
fn test_clear() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    for i in 0..10 {
        map.insert(i, i).expect("invariant broken");
    }
    assert_eq!(map.len(), 10);
    map.clear();
    assert_eq!(map.len(), 0);
    assert!(map.is_empty());
    // After clear, can insert again
    map.insert(42, 99).expect("invariant broken");
    assert_eq!(map.get(&42), Some(&99));
}

// ==================== Stress / edge cases ====================

#[test]
fn test_many_inserts() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    let n = 500;
    for i in 0..n {
        map.insert(i, i * 3).expect("invariant broken");
    }
    assert_eq!(map.len(), n as usize);
    for i in 0..n {
        assert_eq!(map.get(&i), Some(&(i * 3)));
    }
}

#[test]
fn test_insert_remove_cycle() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    for round in 0..5 {
        let base = round * 20;
        for i in base..base + 20 {
            map.insert(i, i).expect("invariant broken");
        }
        for i in base..base + 10 {
            assert_eq!(map.remove(&i), Some(i));
        }
    }
    // 5 rounds × 10 surviving = 50 entries
    assert_eq!(map.len(), 50);
    for round in 0..5 {
        let base = round * 20;
        for i in base..base + 10 {
            assert_eq!(map.get(&i), None);
        }
        for i in base + 10..base + 20 {
            assert_eq!(map.get(&i), Some(&i));
        }
    }
}

#[test]
fn test_string_keys() {
    let mut map: ZiporaHashMap<String, String> = ZiporaHashMap::new().expect("invariant broken");
    map.insert("hello".to_string(), "world".to_string())
        .expect("invariant broken");
    map.insert("foo".to_string(), "bar".to_string())
        .expect("invariant broken");
    assert_eq!(map.get("hello"), Some(&"world".to_string()));
    assert_eq!(map.get("foo"), Some(&"bar".to_string()));
    map.remove("hello");
    assert_eq!(map.get("hello"), None);
    assert_eq!(map.get("foo"), Some(&"bar".to_string()));
}

#[test]
fn test_with_capacity() {
    let mut map: ZiporaHashMap<i32, i32> =
        ZiporaHashMap::with_capacity(64).expect("invariant broken");
    assert!(map.capacity() >= 64);
    for i in 0..64 {
        map.insert(i, i).expect("invariant broken");
    }
    assert_eq!(map.len(), 64);
}

#[test]
fn test_overwrite_many_times() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    for v in 0..100 {
        let old = map.insert(0, v).expect("invariant broken");
        if v == 0 {
            assert_eq!(old, None);
        } else {
            assert_eq!(old, Some(v - 1));
        }
    }
    assert_eq!(map.get(&0), Some(&99));
    assert_eq!(map.len(), 1);
}

#[test]
fn test_remove_then_reinsert_different_value() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().expect("invariant broken");
    map.insert(1, 100).expect("invariant broken");
    map.remove(&1);
    map.insert(1, 200).expect("invariant broken");
    assert_eq!(map.get(&1), Some(&200));
    assert_eq!(map.len(), 1);
}

#[test]
fn test_all_collisions_stress() {
    // All keys hash identically — worst-case linear probing
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(99))
            .expect("invariant broken");

    let n = 50;
    for i in 0..n {
        map.insert(i, i * 7).expect("invariant broken");
    }
    assert_eq!(map.len(), n as usize);
    for i in 0..n {
        assert_eq!(map.get(&i), Some(&(i * 7)));
    }
    // Remove every other key
    for i in (0..n).step_by(2) {
        assert_eq!(map.remove(&i), Some(i * 7));
    }
    assert_eq!(map.len(), (n / 2) as usize);
    for i in (1..n).step_by(2) {
        assert_eq!(map.get(&i), Some(&(i * 7)));
    }
}

// ==================== Strategy gating tests ====================

#[test]
fn test_cache_optimized_returns_not_supported() {
    let config = ZiporaHashMapConfig::cache_optimized();
    let result = ZiporaHashMap::<i32, i32>::with_config(config);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("not yet implemented"));
}

#[test]
fn test_string_optimized_returns_not_supported() {
    let config = ZiporaHashMapConfig::string_optimized();
    let result = ZiporaHashMap::<String, i32>::with_config(config);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("not yet implemented"));
}

// ==================== SmallInline fallback tests ====================

#[test]
fn test_small_inline_basic() {
    let config = ZiporaHashMapConfig::small_inline(16);
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::with_config(config).unwrap();
    for i in 0..16 {
        map.insert(i, i * 10).unwrap();
    }
    assert_eq!(map.len(), 16);
    for i in 0..16 {
        assert_eq!(map.get(&i), Some(&(i * 10)));
    }
}

#[test]
fn test_small_inline_fallback_to_standard() {
    let config = ZiporaHashMapConfig::small_inline(16);
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::with_config(config).unwrap();

    // Fill all 16 inline slots
    for i in 0..16 {
        map.insert(i, i * 10).unwrap();
    }
    assert_eq!(map.len(), 16);

    // Insert 17th element — triggers migration to Standard
    map.insert(16, 160).unwrap();
    assert_eq!(map.len(), 17);

    // All 17 entries must be retrievable
    for i in 0..=16 {
        assert_eq!(
            map.get(&i),
            Some(&(i * 10)),
            "key {} missing after fallback",
            i
        );
    }

    // Further inserts into fallback storage should work
    map.insert(17, 170).unwrap();
    assert_eq!(map.len(), 18);
    assert_eq!(map.get(&17), Some(&170));
}

#[test]
fn test_small_inline_overwrite_before_and_after_fallback() {
    let config = ZiporaHashMapConfig::small_inline(16);
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::with_config(config).unwrap();

    // Insert and overwrite within inline storage
    map.insert(1, 10).unwrap();
    assert_eq!(map.insert(1, 20).unwrap(), Some(10));
    assert_eq!(map.get(&1), Some(&20));

    // Fill rest and trigger fallback
    for i in 2..=16 {
        map.insert(i, i * 10).unwrap();
    }
    map.insert(17, 170).unwrap();

    // Overwrite within fallback storage
    assert_eq!(map.len(), 17);
    assert_eq!(map.get(&1), Some(&20));
}

#[test]
fn test_tombstone_duplicate_key_regression() {
    let config = ZiporaHashMapConfig::default();
    let mut map: ZiporaHashMap<i32, i32, FixedHashBuilder> =
        ZiporaHashMap::with_config_and_hasher(config, FixedHashBuilder(42))
            .expect("invariant broken");

    // All three keys collide and form a probe chain:
    // Slot 1: Key 1
    // Slot 2: Key 2
    // Slot 3: Key 3
    map.insert(1, 10).unwrap();
    map.insert(2, 20).unwrap();
    map.insert(3, 30).unwrap();

    // Remove key 2, creating a tombstone at Slot 2.
    // The probe chain now has a tombstone in the middle:
    // Slot 1: Key 1
    // Slot 2: Tombstone
    // Slot 3: Key 3
    assert_eq!(map.remove(&2), Some(20));

    // Re-insert key 3 with a new value.
    // Previously, the bug would cause the insertion to stop at Slot 2 (Tombstone)
    // and insert key 3 there, creating a duplicate.
    let old_value = map.insert(3, 300).unwrap();

    // We expect the old value (30) to be returned since key 3 already existed in the map.
    assert_eq!(old_value, Some(30));

    // The length of the map should still be 2 (keys 1 and 3).
    assert_eq!(map.len(), 2);

    // We should be able to retrieve the updated value for key 3.
    assert_eq!(map.get(&3), Some(&300));
}

#[test]
fn test_clone_preserves_all_entries() {
    // Test Standard storage clone
    {
        let mut map: ZiporaHashMap<i32, String> = ZiporaHashMap::new().unwrap();
        for i in 0..20 {
            map.insert(i, i.to_string()).unwrap();
        }
        let cloned = map.clone();
        assert_eq!(cloned.len(), map.len());
        for i in 0..20 {
            assert_eq!(cloned.get(&i), map.get(&i));
        }
    }

    // Test SmallInline storage clone (without migration)
    {
        let config = ZiporaHashMapConfig::small_inline(16);
        let mut map: ZiporaHashMap<i32, String> = ZiporaHashMap::with_config(config).unwrap();
        for i in 0..10 {
            map.insert(i, i.to_string()).unwrap();
        }
        let cloned = map.clone();
        assert_eq!(cloned.len(), map.len());
        for i in 0..10 {
            assert_eq!(cloned.get(&i), map.get(&i));
        }
    }

    // Test SmallInline storage clone (with migration/fallback)
    {
        let config = ZiporaHashMapConfig::small_inline(16);
        let mut map: ZiporaHashMap<i32, String> = ZiporaHashMap::with_config(config).unwrap();
        for i in 0..20 {
            map.insert(i, i.to_string()).unwrap();
        }
        let cloned = map.clone();
        assert_eq!(cloned.len(), map.len());
        for i in 0..20 {
            assert_eq!(cloned.get(&i), map.get(&i));
        }
    }
}

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

#[derive(Clone, Debug)]
struct DropTracker(Arc<AtomicUsize>);

impl Drop for DropTracker {
    fn drop(&mut self) {
        self.0.fetch_add(1, Ordering::SeqCst);
    }
}

#[test]
fn test_small_inline_remove_and_clear_drops_values() {
    let drop_counter = Arc::new(AtomicUsize::new(0));
    let config = ZiporaHashMapConfig::small_inline(16);
    let mut map: ZiporaHashMap<i32, DropTracker> = ZiporaHashMap::with_config(config).unwrap();

    for i in 0..5 {
        map.insert(i, DropTracker(Arc::clone(&drop_counter))).unwrap();
    }
    assert_eq!(map.len(), 5);

    // Remove entry 2
    let removed = map.remove(&2);
    assert!(removed.is_some());
    assert_eq!(map.len(), 4);
    assert!(!map.contains_key(&2));
    assert!(map.get(&2).is_none());

    // Drop the removed value
    drop(removed);
    assert_eq!(drop_counter.load(Ordering::SeqCst), 1);

    // Clear map
    map.clear();
    assert_eq!(map.len(), 0);
    assert_eq!(map.iter().count(), 0);
    assert_eq!(drop_counter.load(Ordering::SeqCst), 5); // 1 from remove + 4 from clear
}

#[test]
fn test_get_mut_after_small_inline_migration() {
    let config = ZiporaHashMapConfig::small_inline(16);
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::with_config(config).unwrap();

    // Insert 20 entries to force migration from SmallInline to Standard fallback
    for i in 0..20 {
        map.insert(i, i * 10).unwrap();
    }

    // get_mut on early key (0) should work
    let val_mut = map.get_mut(&0);
    assert!(val_mut.is_some());
    *val_mut.unwrap() = 999;

    assert_eq!(map.get(&0), Some(&999));
}

#[test]
fn test_len_tracking_consistency() {
    let mut map: ZiporaHashMap<i32, i32> = ZiporaHashMap::new().unwrap();
    assert_eq!(map.len(), 0);

    for i in 0..50 {
        map.insert(i, i).unwrap();
        assert_eq!(map.len(), i as usize + 1);
        assert_eq!(map.len(), map.iter().count());
    }

    for i in 0..20 {
        map.remove(&i);
        assert_eq!(map.len(), 50 - (i as usize + 1));
        assert_eq!(map.len(), map.iter().count());
    }

    map.clear();
    assert_eq!(map.len(), 0);
    assert_eq!(map.len(), map.iter().count());
}

#[test]
fn test_migration_panic_safety() {
    use std::hash::Hasher;

    #[derive(Clone, Debug)]
    struct PanicHashKey {
        id: usize,
        counter: Arc<AtomicUsize>,
        panic_on_hash: Arc<AtomicUsize>,
        hash_count: Arc<AtomicUsize>,
    }

    impl PartialEq for PanicHashKey {
        fn eq(&self, other: &Self) -> bool {
            self.id == other.id
        }
    }

    impl Eq for PanicHashKey {}

    impl Hash for PanicHashKey {
        fn hash<H: Hasher>(&self, state: &mut H) {
            let count = self.hash_count.fetch_add(1, Ordering::SeqCst) + 1;
            if count == self.panic_on_hash.load(Ordering::SeqCst) {
                panic!("Simulated hash panic during migration");
            }
            self.id.hash(state);
        }
    }

    impl Drop for PanicHashKey {
        fn drop(&mut self) {
            self.counter.fetch_add(1, Ordering::SeqCst);
        }
    }

    let drop_counter = Arc::new(AtomicUsize::new(0));
    let hash_counter = Arc::new(AtomicUsize::new(0));
    let panic_on_hash = Arc::new(AtomicUsize::new(9999));

    let config = ZiporaHashMapConfig::small_inline(16);
    let mut map: ZiporaHashMap<PanicHashKey, usize> = ZiporaHashMap::with_config(config).unwrap();

    // Insert 16 elements into SmallInline
    for i in 0..16 {
        map.insert(
            PanicHashKey {
                id: i,
                counter: Arc::clone(&drop_counter),
                panic_on_hash: Arc::clone(&panic_on_hash),
                hash_count: Arc::clone(&hash_counter),
            },
            i,
        )
        .unwrap();
    }

    // Now set panic_on_hash to trigger during migration loop
    panic_on_hash.store(hash_counter.load(Ordering::SeqCst) + 2, Ordering::SeqCst);

    let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        map.insert(
            PanicHashKey {
                id: 16,
                counter: Arc::clone(&drop_counter),
                panic_on_hash: Arc::clone(&panic_on_hash),
                hash_count: Arc::clone(&hash_counter),
            },
            16,
        )
    }));

    assert!(res.is_err());
    // Dropping map after panic unwinding must not cause double-free/double-drop
    drop(map);
}

#[test]
fn test_non_power_of_two_capacity_rounds_up() {
    // Regression (plan.md 7.2): with_capacity(100) used to produce mask 99,
    // whose probe sequence `(index + i) & 99` misses slots and could fail
    // resize with "Failed to reinsert during resize".
    let mut map: ZiporaHashMap<u32, u32> = ZiporaHashMap::with_capacity(100).unwrap();
    for i in 0..300u32 {
        map.insert(i, i * 2).unwrap();
    }
    assert_eq!(map.len(), 300);
    for i in 0..300u32 {
        assert_eq!(map.get(&i), Some(&(i * 2)), "key {} lost", i);
    }
}

#[test]
fn test_clear_then_reuse_standard() {
    // Verifies clear_standard semantics (plan.md 7.2): after clear() the map
    // is empty and fully usable again (insert/get/len).
    let mut map: ZiporaHashMap<u32, u32> = ZiporaHashMap::new().unwrap();
    for i in 0..100u32 {
        map.insert(i, i).unwrap();
    }
    map.clear();
    assert_eq!(map.len(), 0);
    assert!(map.is_empty());
    assert_eq!(map.get(&5), None);

    for i in 0..100u32 {
        map.insert(i, i + 1).unwrap();
    }
    assert_eq!(map.len(), 100);
    for i in 0..100u32 {
        assert_eq!(map.get(&i), Some(&(i + 1)));
    }
}