opthash 0.10.2

Rust implementations of Elastic Hashing and Funnel 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
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
use std::hash::{BuildHasher, Hash};
use std::mem::{self, MaybeUninit};
use std::ops::Range;
use std::slice;

use allocator_api2::alloc::{Allocator, Global, Layout};
use equivalent::Equivalent;

use crate::common::DefaultHashBuilder;
use crate::common::arena::{self, Arena, ArenaSlots, SlotEntry};
use crate::common::config::{GROUP_SIZE, INITIAL_CAPACITY};
use crate::common::control::{self, CTRL_EMPTY, CTRL_TOMBSTONE, ControlByte};
use crate::common::error::TryReserveError;
use crate::common::iter::RegionCursor;
use crate::common::math::{self, align, capacity, cast, probe};
use crate::common::simd;
use crate::map::{self, RawTable};
use crate::set;

/// Upper bound on `reserve_fraction`;
/// level capacities become unstable beyond this load factor.
pub(crate) const MAX_FUNNEL_RESERVE_FRACTION: f64 = 1.0 / 8.0;

/// One funnel level `A_i` (paper ยง5). Fixed grid of `ฮฒ`-sized buckets `A_{i,j}`;
/// inserts hash to one bucket and probe within it. Overflow spills to `A_{i+1}`
/// (or the special array `A_{ฮฑ+1}`).
struct BucketLevel<T> {
    ctrl_ptr: *mut u8,
    data_ptr: *mut MaybeUninit<T>,
    capacity: u32,
    bucket_count_mask: u32,
    bucket_size_log2: u32,
    salt: u32,
    len: u32,
    tombstones: u32,
}

unsafe impl<T: Send> Send for BucketLevel<T> {}
unsafe impl<T: Sync> Sync for BucketLevel<T> {}

impl<T> ArenaSlots<T> for BucketLevel<T> {
    #[inline]
    fn ctrl_ptr(&self) -> *mut u8 {
        self.ctrl_ptr
    }
    #[inline]
    fn data_ptr(&self) -> *mut MaybeUninit<T> {
        self.data_ptr
    }
    #[inline]
    fn capacity(&self) -> usize {
        self.capacity as usize
    }
}

impl<T> BucketLevel<T> {
    /// Stamps a fresh descriptor at the given arena ptrs.
    /// Caller advances the offset cursor.
    fn new_at(
        level_idx: usize,
        bucket_count: u32,
        bucket_width: u32,
        ctrl_ptr: *mut u8,
        data_ptr: *mut MaybeUninit<T>,
    ) -> Self {
        let cap = bucket_count.saturating_mul(bucket_width);
        Self {
            ctrl_ptr,
            data_ptr,
            capacity: cap,
            bucket_count_mask: bucket_count.saturating_sub(1),
            bucket_size_log2: bucket_width.trailing_zeros(),
            salt: math::level_salt(level_idx),
            len: 0,
            tombstones: 0,
        }
    }

    #[inline]
    #[allow(clippy::cast_possible_truncation)]
    fn bucket_index(&self, key_hash: u64) -> usize {
        ((key_hash as u32) ^ self.salt) as usize & self.bucket_count_mask as usize
    }

    /// Slot index range covering all entries in `bucket_idx`.
    #[inline]
    fn bucket_range(&self, bucket_idx: usize) -> Range<usize> {
        let start = bucket_idx << self.bucket_size_log2;
        let size = 1usize << self.bucket_size_log2;
        start..start + size
    }

    /// Paper ยง5 attempted insertion: hash `key_hash` to one bucket `A_{i,j}`,
    /// return the first empty slot in that bucket (or `None` if full).
    fn first_free_in_bucket(&self, key_hash: u64) -> Option<usize> {
        if self.len >= self.capacity {
            return None;
        }
        let bucket_idx = self.bucket_index(key_hash);
        let bucket_range = self.bucket_range(bucket_idx);
        debug_assert_eq!(bucket_range.start % GROUP_SIZE, 0);
        if !bucket_range.start.is_multiple_of(GROUP_SIZE) {
            unsafe { std::hint::unreachable_unchecked() };
        }
        let group_idx = bucket_range.start / GROUP_SIZE;
        let group_ptr = unsafe { self.ctrl_ptr().add(group_idx * GROUP_SIZE) };
        unsafe { simd::free_mask_group(group_ptr) }
            .lowest()
            .map(|offset| bucket_range.start + offset)
    }

    /// Erase slot: become `CTRL_EMPTY` if the bucket has any EMPTY byte
    /// (probe chain terminates here), else `CTRL_TOMBSTONE`.
    /// Returns whether a tombstone was written.
    #[inline]
    fn erase(&mut self, idx: usize) -> bool {
        let group_idx = idx / GROUP_SIZE;
        let gp = unsafe { self.ctrl_ptr().add(group_idx * GROUP_SIZE) };
        if unsafe { simd::eq_mask_group(gp, CTRL_EMPTY).any() } {
            self.set_control(idx, CTRL_EMPTY);
            false
        } else {
            self.set_control(idx, CTRL_TOMBSTONE);
            true
        }
    }
}

impl<K, V> BucketLevel<SlotEntry<K, V>> {
    /// Probe one bucket for `key`. `StopSearch` on EMPTY: bucket never
    /// overflowed, so the key isn't at a deeper level. Pass `Some(out)`
    /// to record the first free slot; `None` for lookup.
    #[inline]
    fn find_in_bucket<Q>(
        &self,
        key_hash: u64,
        key_fingerprint: u8,
        key: &Q,
        slot_out: Option<&mut Option<usize>>,
    ) -> LookupStep
    where
        Q: Equivalent<K> + ?Sized,
    {
        let wants_free = matches!(&slot_out, Some(out) if out.is_none());
        if self.len == 0 {
            if self.capacity == 0 {
                return LookupStep::Continue;
            }
            if wants_free {
                let bucket_idx = self.bucket_index(key_hash);
                let slot_idx = bucket_idx << self.bucket_size_log2;
                if let Some(out) = slot_out {
                    *out = Some(slot_idx);
                }
            }
            if self.tombstones == 0 {
                return LookupStep::StopSearch;
            }
            return LookupStep::Continue;
        }
        let bucket_idx = self.bucket_index(key_hash);
        let bucket_range = self.bucket_range(bucket_idx);
        debug_assert_eq!(bucket_range.start % GROUP_SIZE, 0);
        if !bucket_range.start.is_multiple_of(GROUP_SIZE) {
            unsafe { std::hint::unreachable_unchecked() };
        }
        let group_idx = bucket_range.start / GROUP_SIZE;
        let group_ptr = unsafe { self.ctrl_ptr().add(group_idx * GROUP_SIZE) };
        let match_mask = unsafe { simd::eq_mask_group(group_ptr, key_fingerprint) };
        for relative_idx in match_mask {
            let slot_idx = bucket_range.start + relative_idx;
            let entry = unsafe { self.get_ref(slot_idx) };
            if key.equivalent(&entry.key) {
                return LookupStep::Found(slot_idx);
            }
        }
        if wants_free {
            let free_mask = unsafe { simd::free_mask_group(group_ptr) };
            if let Some(o) = free_mask.lowest()
                && let Some(out) = slot_out
            {
                *out = Some(bucket_range.start + o);
            }
        }
        if unsafe { simd::eq_mask_group(group_ptr, CTRL_EMPTY).any() } {
            LookupStep::StopSearch
        } else {
            LookupStep::Continue
        }
    }
}

/// Per-key odd-step probe over pow2 group count (paper ยง5 `SpecialPrimary`).
/// Step coprime to `group_count` โ‡’ permutation over all groups.
struct ProbeSeq {
    group: usize,
    step: usize,
}

impl ProbeSeq {
    #[inline]
    fn new(group: usize, step: usize) -> Self {
        Self { group, step }
    }

    #[inline]
    fn advance(&mut self, mask: usize) {
        self.group = (self.group + self.step) & mask;
    }
}

/// Half `B` of the special array `A_{ฮฑ+1}` (paper ยง5):
/// uniform-probing table capped at `primary_probe_limit` โ‰ˆ log log n probes.
/// SIMD-group open addressing with per-key odd-step probing over pow2 `group_count`
/// (step coprime to `group_count` โ‡’ permutation over all groups).
struct SpecialPrimary<T> {
    ctrl_ptr: *mut u8,
    data_ptr: *mut MaybeUninit<T>,
    capacity: u32,
    group_count_mask: u32,
    len: u32,
    tombstones: u32,
}

unsafe impl<T: Send> Send for SpecialPrimary<T> {}
unsafe impl<T: Sync> Sync for SpecialPrimary<T> {}

impl<T> ArenaSlots<T> for SpecialPrimary<T> {
    #[inline]
    fn ctrl_ptr(&self) -> *mut u8 {
        self.ctrl_ptr
    }
    #[inline]
    fn data_ptr(&self) -> *mut MaybeUninit<T> {
        self.data_ptr
    }
    #[inline]
    fn capacity(&self) -> usize {
        self.capacity as usize
    }
}

impl<T> SpecialPrimary<T> {
    /// Stamps a fresh primary descriptor.
    /// `group_count_mask` = `group_count - 1` (pow2-1) so probes wrap `& mask`.
    fn new_at(
        cap: u32,
        group_count_mask: u32,
        ctrl_ptr: *mut u8,
        data_ptr: *mut MaybeUninit<T>,
    ) -> Self {
        Self {
            ctrl_ptr,
            data_ptr,
            capacity: cap,
            group_count_mask,
            len: 0,
            tombstones: 0,
        }
    }

    #[inline]
    fn group_count(&self) -> usize {
        if self.capacity == 0 {
            0
        } else {
            self.capacity as usize / GROUP_SIZE
        }
    }
    #[inline]
    fn group_start(&self, key_hash: u64) -> usize {
        probe::hash_to_usize(key_hash.rotate_left(11)) & self.group_count_mask as usize
    }
    /// Per-key odd step over the pow2 `group_count`. The `| 1` forces odd โ‡’
    /// coprime to pow2 โ‡’ `(group_idx + step) & mask` visits every group
    /// within `group_count` iterations.
    #[inline]
    fn group_step(&self, key_hash: u64) -> usize {
        (probe::hash_to_usize(key_hash.rotate_left(43)) | 1) & self.group_count_mask as usize
    }

    /// Erase slot: drop tombstone unless the group has free space.
    #[inline]
    fn erase(&mut self, idx: usize) -> bool {
        let group_idx = idx / GROUP_SIZE;
        let gp = unsafe { self.ctrl_ptr().add(group_idx * GROUP_SIZE) };
        if unsafe { simd::eq_mask_group(gp, CTRL_EMPTY).any() } {
            self.set_control(idx, CTRL_EMPTY);
            false
        } else {
            self.set_control(idx, CTRL_TOMBSTONE);
            true
        }
    }
}

/// Half `C` of the special array `A_{ฮฑ+1}` (paper ยง5):
/// two-choice table with buckets of size `2 * primary_probe_limit` โ‰ˆ 2 log log n.
/// Reached only when a key exhausts the primary's probe budget.
struct SpecialFallback<T> {
    ctrl_ptr: *mut u8,
    data_ptr: *mut MaybeUninit<T>,
    capacity: u32,
    bucket_count: u32,
    bucket_size_log2: u32,
    len: u32,
    tombstones: u32,
}

unsafe impl<T: Send> Send for SpecialFallback<T> {}
unsafe impl<T: Sync> Sync for SpecialFallback<T> {}

impl<T> ArenaSlots<T> for SpecialFallback<T> {
    #[inline]
    fn ctrl_ptr(&self) -> *mut u8 {
        self.ctrl_ptr
    }
    #[inline]
    fn data_ptr(&self) -> *mut MaybeUninit<T> {
        self.data_ptr
    }
    #[inline]
    fn capacity(&self) -> usize {
        self.capacity as usize
    }
}

impl<T> SpecialFallback<T> {
    /// Stamps a fresh fallback descriptor with two-choice bucket geometry.
    fn new_at(
        cap: u32,
        bucket_count: u32,
        bucket_size_log2: u32,
        ctrl_ptr: *mut u8,
        data_ptr: *mut MaybeUninit<T>,
    ) -> Self {
        Self {
            ctrl_ptr,
            data_ptr,
            capacity: cap,
            bucket_count,
            bucket_size_log2,
            len: 0,
            tombstones: 0,
        }
    }

    #[inline]
    fn bucket_range(&self, bucket_idx: usize) -> Range<usize> {
        let start = bucket_idx << self.bucket_size_log2;
        let size = 1usize << self.bucket_size_log2;
        let end = (start + size).min(self.capacity as usize);
        start..end
    }
    #[inline]
    fn bucket_a(&self, key_hash: u64) -> usize {
        probe::hash_to_usize(key_hash.rotate_left(19)) % self.bucket_count as usize
    }
    #[inline]
    fn bucket_b(&self, key_hash: u64) -> usize {
        probe::hash_to_usize(key_hash.rotate_left(37)) % self.bucket_count as usize
    }

    /// Erase slot: drop tombstone unless the group has free space.
    #[inline]
    fn erase(&mut self, idx: usize) -> bool {
        let group_idx = idx / GROUP_SIZE;
        let gp = unsafe { self.ctrl_ptr().add(group_idx * GROUP_SIZE) };
        if unsafe { simd::eq_mask_group(gp, CTRL_EMPTY).any() } {
            self.set_control(idx, CTRL_EMPTY);
            false
        } else {
            self.set_control(idx, CTRL_TOMBSTONE);
            true
        }
    }
}

/// Combines the special primary (probed first) and the special fallback
/// (when primary hits its probe limit). Together they catch keys that
/// overflowed every bucket level.
struct SpecialArray<T> {
    primary: SpecialPrimary<T>,
    fallback: SpecialFallback<T>,
    total_len: usize,
}

impl<T> SpecialArray<T> {
    /// Drain primary + fallback, calling `f` on each entry. Each slot's
    /// ctrl is cleared *before* the move so an `f` panic leaves no
    /// OCCUPIED ctrl for the map's drop to double-drop.
    fn drain_occupied_with<F: FnMut(T)>(&mut self, mut f: F) {
        self.primary.drain_values_and_clear(&mut f);
        self.fallback.drain_values_and_clear(f);
    }
}

/// Where in the funnel structure a key/slot lives. Returned by lookups,
/// consumed by inserts / removes to avoid recomputing the location.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotLocation {
    Level { level_idx: usize, slot_idx: usize },
    SpecialPrimary { slot_idx: usize },
    SpecialFallback { slot_idx: usize },
}

/// Out-parameter for free-slot tracking during probes.
/// `None` = lookup-only; `Some(out)` = also record the first free
/// `SlotLocation` seen. Written once; ignored if `*out` is already `Some`.
type FreeSlot<'a> = Option<&'a mut Option<SlotLocation>>;

/// Outcome of probing one bucket / group during lookup.
/// - `Found(slot_idx)`: key matched at slot.
/// - `Continue`: bucket has tombstones; keep probing for the key elsewhere.
/// - `StopSearch`: bucket has free space and no tombstones โ€” key cannot
///   exist further along this hash chain, abort the search.
enum LookupStep {
    Found(usize),
    Continue,
    StopSearch,
}

/// Why a single-pass level probe missed, deciding whether overflow to the
/// special array is possible.
enum LevelMiss {
    /// An EMPTY byte ended the chain; no overflow to special possible.
    ChainClean,
    /// Levels exhausted without a clean stop; key may be in the special array.
    MayContinue,
}

/// Open-addressed funnel-hashing backend for the generic [`map::HashMap`]
/// shell. See [`FunnelHashMap`] for the public map type.
///
/// Capacity is split between a stack of bucket-grouped `levels` (each level
/// half the size of the previous) and a `special` array catching overflow.
/// Inserts try level 0 first, then descend to deeper levels, then to
/// `special.primary`, then `special.fallback`. Lookups follow the same
/// order. The funnel structure trades a small probe budget per level for
/// hard worst-case guarantees on lookup cost.
///
/// **Lower bound**: paper ยง4 proves any greedy open-addressing scheme needs
/// `ฮฉ(logยฒ ฮดโปยน)` worst-case probes (`ฮด` = empty fraction). Funnel matches
/// this asymptotically โ€” no constant-factor rewrite can do better.
pub struct FunnelTable<K, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> {
    /// Level descriptors (bucket-grouped).
    levels: BucketLevelSlice<K, V>,
    /// Special array descriptor.
    special: SpecialArray<SlotEntry<K, V>>,
    /// Total live entries.
    len: usize,
    /// Total slot count across all levels + special arrays.
    total_slots: usize,
    /// Insert count that triggers resize.
    max_insertions: usize,
    /// Slot reserve fraction.
    reserve_fraction: f64,
    /// Cap on groups probed in the special primary before fallback.
    primary_probe_limit: usize,
    /// Highest level index ever written.
    max_populated_level: usize,
    hash_builder: S,
    alloc: A,
    /// Single allocation: [`ctrl_L0|ctrl_L1|...|ctrl_SP|ctrl_SF`][pad][`slots_L0|...|slots_SP|slots_SF`].
    arena: Arena,
}

unsafe impl<K: Send, V: Send, S: Send, A: Allocator + Clone + Send> Send
    for FunnelTable<K, V, S, A>
{
}
unsafe impl<K: Sync, V: Sync, S: Sync, A: Allocator + Clone + Sync> Sync
    for FunnelTable<K, V, S, A>
{
}

impl<K, V, S, A: Allocator + Clone> Drop for FunnelTable<K, V, S, A> {
    fn drop(&mut self) {
        let arena = mem::replace(&mut self.arena, Arena::empty());
        let guard = arena::DeallocGuard::new(arena, &self.alloc);
        for level in &mut self.levels {
            level.drop_values();
        }
        self.special.primary.drop_values();
        self.special.fallback.drop_values();
        drop(guard);
    }
}

// ---------------------------------------------------------------------------
// Public type aliases. The generic [`map::HashMap`] shell supplies the public
// API; these names keep `FunnelHashMap` and its iterator/entry types nameable
// (and re-exportable from `lib.rs` / `set.rs`).
// ---------------------------------------------------------------------------

/// Open-addressed hash map using funnel hashing.
pub type FunnelHashMap<K, V, S = DefaultHashBuilder, A = Global> =
    map::HashMap<K, V, FunnelTable<K, V, S, A>>;

/// A view into a single entry, occupied or vacant.
pub type FunnelEntry<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::Entry<'a, K, V, FunnelTable<K, V, S, A>>;
/// View of an occupied entry.
pub type FunnelOccupiedEntry<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::OccupiedEntry<'a, K, V, FunnelTable<K, V, S, A>>;
/// View of a vacant entry.
pub type FunnelVacantEntry<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::VacantEntry<'a, K, V, FunnelTable<K, V, S, A>>;
/// Error returned by `try_insert` on key collision.
pub type FunnelOccupiedError<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::OccupiedError<'a, K, V, FunnelTable<K, V, S, A>>;
/// Borrowing iterator over `(&K, &V)`.
pub type FunnelIter<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::Iter<'a, K, V, FunnelTable<K, V, S, A>>;
/// Borrowing iterator over `(&K, &mut V)`.
pub type FunnelIterMut<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::IterMut<'a, K, V, FunnelTable<K, V, S, A>>;
/// Consuming iterator over owned `(K, V)`.
pub type FunnelIntoIter<K, V, S = DefaultHashBuilder, A = Global> =
    map::IntoIter<K, V, FunnelTable<K, V, S, A>>;
/// `&K` iterator.
pub type FunnelKeys<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::Keys<'a, K, V, FunnelTable<K, V, S, A>>;
/// `&V` iterator.
pub type FunnelValues<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::Values<'a, K, V, FunnelTable<K, V, S, A>>;
/// `&mut V` iterator.
pub type FunnelValuesMut<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::ValuesMut<'a, K, V, FunnelTable<K, V, S, A>>;
/// Owned `K` iterator.
pub type FunnelIntoKeys<K, V, S = DefaultHashBuilder, A = Global> =
    map::IntoKeys<K, V, FunnelTable<K, V, S, A>>;
/// Owned `V` iterator.
pub type FunnelIntoValues<K, V, S = DefaultHashBuilder, A = Global> =
    map::IntoValues<K, V, FunnelTable<K, V, S, A>>;
/// Draining iterator that empties the map.
pub type FunnelDrain<'a, K, V, S = DefaultHashBuilder, A = Global> =
    map::Drain<'a, K, V, FunnelTable<K, V, S, A>>;
/// Iterator yielding entries removed by `extract_if`.
pub type FunnelExtractIf<'a, K, V, F, S = DefaultHashBuilder, A = Global> =
    map::ExtractIf<'a, K, V, FunnelTable<K, V, S, A>, F>;

/// Hash set using funnel hashing.
pub type FunnelHashSet<T, S = DefaultHashBuilder, A = Global> =
    set::HashSet<T, FunnelTable<T, (), S, A>>;
/// Borrowing iterator over set values.
pub type FunnelSetIter<'a, T, S = DefaultHashBuilder, A = Global> =
    set::Iter<'a, T, FunnelTable<T, (), S, A>>;
/// Consuming iterator over set values.
pub type FunnelSetIntoIter<T, S = DefaultHashBuilder, A = Global> =
    set::IntoIter<T, FunnelTable<T, (), S, A>>;
/// Draining iterator that empties the set.
pub type FunnelSetDrain<'a, T, S = DefaultHashBuilder, A = Global> =
    set::Drain<'a, T, FunnelTable<T, (), S, A>>;
/// Iterator yielding values removed by set `extract_if`.
pub type FunnelSetExtractIf<'a, T, S = DefaultHashBuilder, A = Global> =
    set::ExtractIf<'a, T, FunnelTable<T, (), S, A>>;
/// Iterator over values present only in the first set.
pub type FunnelDifference<'a, T, S = DefaultHashBuilder, A = Global> =
    set::Difference<'a, T, FunnelTable<T, (), S, A>>;
/// Iterator over values present in both sets.
pub type FunnelIntersection<'a, T, S = DefaultHashBuilder, A = Global> =
    set::Intersection<'a, T, FunnelTable<T, (), S, A>>;
/// Iterator over values present in exactly one set.
pub type FunnelSymmetricDifference<'a, T, S = DefaultHashBuilder, A = Global> =
    set::SymmetricDifference<'a, T, FunnelTable<T, (), S, A>>;
/// Iterator over values present in either set.
pub type FunnelUnion<'a, T, S = DefaultHashBuilder, A = Global> =
    set::Union<'a, T, FunnelTable<T, (), S, A>>;
/// A view into a single set entry.
pub type FunnelSetEntry<'a, T, S = DefaultHashBuilder, A = Global> =
    set::Entry<'a, T, FunnelTable<T, (), S, A>>;
/// View of an occupied set entry.
pub type FunnelSetOccupiedEntry<'a, T, S = DefaultHashBuilder, A = Global> =
    set::OccupiedEntry<'a, T, FunnelTable<T, (), S, A>>;
/// View of a vacant set entry.
pub type FunnelSetVacantEntry<'a, T, S = DefaultHashBuilder, A = Global> =
    set::VacantEntry<'a, T, FunnelTable<T, (), S, A>>;

/// Boxed level descriptors for one funnel arena build.
type BucketLevelSlice<K, V> = Box<[BucketLevel<SlotEntry<K, V>>]>;

/// Full result of a funnel arena build: arena + level + special descriptors.
type FunnelArenaBuild<K, V> = (Arena, BucketLevelSlice<K, V>, SpecialArray<SlotEntry<K, V>>);

/// [`FunnelArenaBuild`] minus the arena, returned by
/// [`FunnelGeometry::build_regions`] so the caller deallocates on error.
type FunnelArenaInner<K, V> = (BucketLevelSlice<K, V>, SpecialArray<SlotEntry<K, V>>);

/// Power-of-two-rounded layout sizes for one funnel map: levels + the two
/// special arrays. Derives every rounded size once in [`new`](Self::new), then
/// owns the build/alloc steps so callers never re-thread or re-round them.
struct FunnelGeometry<'a> {
    level_bucket_counts: &'a [usize],
    /// `bucket_width` rounded up to a power of two.
    bucket_width: usize,
    primary_ctrl: usize,
    fallback_ctrl: usize,
    fallback_bucket_size: usize,
}

impl<'a> FunnelGeometry<'a> {
    /// Rounds the raw capacities to their final layout sizes once. `bucket_width`
    /// rounds up to a power of two; the special capacities to their ctrl-byte
    /// extents (idempotent if already rounded).
    fn new(
        level_bucket_counts: &'a [usize],
        bucket_width: usize,
        special_primary_capacity: usize,
        special_fallback_capacity: usize,
        fallback_bucket_size: usize,
    ) -> Self {
        Self {
            level_bucket_counts,
            bucket_width: bucket_width.next_power_of_two(),
            primary_ctrl: align::round_up_to_pow2_groups(special_primary_capacity),
            fallback_ctrl: align::round_up_to_group(special_fallback_capacity),
            fallback_bucket_size,
        }
    }

    /// Total control-byte count across levels + both special arrays. Checked
    /// throughout: a fallible caller (`try_resize`/`try_reserve`) gets
    /// `CapacityOverflow` rather than a wrapped under-count.
    fn total_ctrl(&self) -> Result<usize, TryReserveError> {
        let mut sum: usize = 0;
        for &bc in self.level_bucket_counts {
            let bc = if bc == 0 {
                0
            } else {
                bc.checked_next_power_of_two()
                    .ok_or(TryReserveError::CapacityOverflow)?
            };
            let part = bc
                .checked_mul(self.bucket_width)
                .ok_or(TryReserveError::CapacityOverflow)?;
            sum = sum
                .checked_add(part)
                .ok_or(TryReserveError::CapacityOverflow)?;
        }
        sum.checked_add(self.primary_ctrl)
            .and_then(|s| s.checked_add(self.fallback_ctrl))
            .ok_or(TryReserveError::CapacityOverflow)
    }

    /// Stamps level + special descriptors from the arena base into a single
    /// contiguous allocation:
    /// `[ctrls_L0|...|sp_ctrl|sf_ctrl][pad][slots_L0|...|sf_slots]`.
    fn build_regions<K, V>(
        &self,
        arena_base: *mut u8,
        data_base_off: usize,
    ) -> Result<FunnelArenaInner<K, V>, TryReserveError> {
        let mut cursor = arena::LayoutCursor::<SlotEntry<K, V>>::new(arena_base, data_base_off)?;

        let mut levels: Vec<BucketLevel<SlotEntry<K, V>>> = Vec::new();
        levels
            .try_reserve_exact(self.level_bucket_counts.len())
            .map_err(|_| TryReserveError::AllocError)?;
        let bw32 =
            u32::try_from(self.bucket_width).map_err(|_| TryReserveError::CapacityOverflow)?;
        for (level_idx, &bc_raw) in self.level_bucket_counts.iter().enumerate() {
            let bc = u32::try_from(if bc_raw == 0 {
                0
            } else {
                bc_raw.next_power_of_two()
            })
            .map_err(|_| TryReserveError::CapacityOverflow)?;
            let cap = bc.saturating_mul(bw32);
            // SAFETY: the arena was allocated for the layout these region caps sum to.
            let (ctrl_ptr, data_ptr) = unsafe { cursor.reserve(cap)? };
            levels.push(BucketLevel::new_at(level_idx, bc, bw32, ctrl_ptr, data_ptr));
        }

        let primary_cap =
            u32::try_from(self.primary_ctrl).map_err(|_| TryReserveError::CapacityOverflow)?;
        let primary_gc_mask = u32::try_from(self.primary_ctrl / GROUP_SIZE)
            .map_err(|_| TryReserveError::CapacityOverflow)?
            .wrapping_sub(1);
        // SAFETY: as above.
        let (primary_ctrl_ptr, primary_data_ptr) = unsafe { cursor.reserve(primary_cap)? };
        let primary = SpecialPrimary::new_at(
            primary_cap,
            primary_gc_mask,
            primary_ctrl_ptr,
            primary_data_ptr,
        );

        let fallback_cap =
            u32::try_from(self.fallback_ctrl).map_err(|_| TryReserveError::CapacityOverflow)?;
        let fb_size = self.fallback_bucket_size.next_power_of_two();
        let fb_count = u32::try_from(if fb_size == 0 {
            0
        } else {
            self.fallback_ctrl.div_ceil(fb_size)
        })
        .map_err(|_| TryReserveError::CapacityOverflow)?;
        let fb_log2 = u32::try_from(fb_size)
            .map_err(|_| TryReserveError::CapacityOverflow)?
            .trailing_zeros();
        // SAFETY: as above.
        let (fallback_ctrl_ptr, fallback_data_ptr) = unsafe { cursor.reserve(fallback_cap)? };
        let fallback = SpecialFallback::new_at(
            fallback_cap,
            fb_count,
            fb_log2,
            fallback_ctrl_ptr,
            fallback_data_ptr,
        );

        Ok((
            levels.into_boxed_slice(),
            SpecialArray {
                primary,
                fallback,
                total_len: 0,
            },
        ))
    }

    /// Fallible single-arena builder: allocates, stamps regions, deallocates on
    /// error (`Arena` has no `Drop`, so a bare `?` would leak).
    fn try_alloc<K, V, A: Allocator + Clone>(
        &self,
        alloc: &A,
    ) -> Result<FunnelArenaBuild<K, V>, TryReserveError> {
        let total_ctrl = self.total_ctrl()?;
        let (arena_layout, data_base_off) = arena::layout_for::<K, V>(total_ctrl)?;
        let arena = Arena::try_allocate_with_ctrl_zeroed(arena_layout, total_ctrl, alloc)?;
        match self.build_regions::<K, V>(arena.as_ptr(), data_base_off) {
            Ok((levels, special)) => Ok((arena, levels, special)),
            Err(e) => {
                arena.deallocate(alloc);
                Err(e)
            }
        }
    }

    /// Infallible [`try_alloc`](Self::try_alloc); aborts via `handle_alloc_error`.
    fn alloc<K, V, A: Allocator + Clone>(&self, alloc: &A) -> FunnelArenaBuild<K, V> {
        self.try_alloc(alloc).unwrap_or_else(|_| {
            let layout = match self
                .total_ctrl()
                .and_then(|tc| arena::layout_for::<K, V>(tc).map(|(layout, _)| layout))
            {
                Ok(layout) => layout,
                Err(_) => Layout::from_size_align(1, 1).unwrap(),
            };
            allocator_api2::alloc::handle_alloc_error(layout)
        })
    }
}

/// A funnel map's regions (bucket levels + the special array), bundled so
/// [`arena::ArenaDropGuard`] can drop their values for panic-safe `clone`.
struct FunnelRegions<K, V> {
    levels: BucketLevelSlice<K, V>,
    special: SpecialArray<SlotEntry<K, V>>,
}

impl<K, V> arena::RegionSet for FunnelRegions<K, V> {
    fn drop_all_values(&mut self) {
        for level in &mut self.levels {
            level.drop_values();
        }
        self.special.primary.drop_values();
        self.special.fallback.drop_values();
    }
}

impl<K, V, S, A> FunnelTable<K, V, S, A>
where
    K: Eq + Hash,
    S: BuildHasher,
    A: Allocator + Clone,
{
    /// Full constructor. `resize` also calls this with the existing
    /// `hash_builder` and allocator so all keys keep the same hash sequence
    /// across grows.
    ///
    /// # Panics
    ///
    /// Panics if no representable capacity satisfies the requested budget.
    #[must_use]
    pub fn with_capacity_and_reserve_fraction_and_hasher_in(
        capacity: usize,
        reserve_fraction: f64,
        hash_builder: S,
        alloc: A,
    ) -> Self {
        // Paper ยง5 precondition: ฮด โ‰ค 1/8.
        let reserve_fraction =
            capacity::sanitize_reserve_fraction(reserve_fraction).min(MAX_FUNNEL_RESERVE_FRACTION);
        let total_slots = if capacity == 0 {
            0
        } else {
            capacity::capacity_for(INITIAL_CAPACITY, capacity, reserve_fraction)
                .expect("capacity overflow")
        };
        let max_insertions = capacity::max_insertions(total_slots, reserve_fraction);

        let level_count = compute_level_count(reserve_fraction);
        let bucket_width = align::round_up_to_group(compute_bucket_width(reserve_fraction));
        let primary_probe_limit = probe::log_log_probe_limit(total_slots).max(1);

        let mut special_capacity =
            choose_special_capacity(total_slots, reserve_fraction, bucket_width);
        let mut main_capacity = total_slots.saturating_sub(special_capacity);
        let main_remainder = main_capacity % bucket_width.max(1);
        if main_remainder != 0 {
            main_capacity = main_capacity.saturating_sub(main_remainder);
            special_capacity = total_slots.saturating_sub(main_capacity);
        }

        let total_main_buckets = main_capacity.checked_div(bucket_width).unwrap_or(0);
        let level_bucket_counts = partition_funnel_buckets(total_main_buckets, level_count);
        let fallback_bucket_size = (primary_probe_limit.saturating_mul(2)).max(2);
        let primary_ctrl = align::round_up_to_pow2_groups(special_capacity.div_ceil(2));
        let fallback_ctrl =
            align::round_up_to_group(special_capacity.saturating_sub(special_capacity.div_ceil(2)));

        let (arena, levels, special) = FunnelGeometry::new(
            &level_bucket_counts,
            bucket_width,
            primary_ctrl,
            fallback_ctrl,
            fallback_bucket_size,
        )
        .alloc(&alloc);

        Self {
            levels,
            special,
            len: 0,
            total_slots,
            max_insertions,
            reserve_fraction,
            primary_probe_limit,
            max_populated_level: 0,
            hash_builder,
            alloc,
            arena,
        }
    }

    /// Round up to the smallest capacity whose `max_insertions` accommodates
    /// `needed` live entries. Returns `None` if no representable capacity
    /// suffices.
    fn grow_capacity_for(&self, needed: usize) -> Option<usize> {
        capacity::capacity_for(
            self.total_slots.max(INITIAL_CAPACITY),
            needed,
            self.reserve_fraction,
        )
    }

    /// Post-lookup insert for a key known to be absent. Returns the chosen
    /// slot so the caller can borrow into it without re-probing.
    fn insert_for_vacant_entry(&mut self, key: K, value: V, key_hash: u64) -> SlotLocation {
        let key_fingerprint = control::control_fingerprint(key_hash);

        let mut location = if self.len < self.max_insertions {
            self.choose_slot_for_new_key(key_hash)
        } else {
            None
        };

        if location.is_none() {
            let new_capacity = if self.total_slots == 0 {
                INITIAL_CAPACITY
            } else {
                self.total_slots.saturating_mul(2)
            };
            self.resize(new_capacity);
            location = Some(
                self.choose_slot_for_new_key(key_hash)
                    .expect("no free slot found after resize"),
            );
        }

        let final_location = location.expect("location set above");
        self.place_new_entry(final_location, key, value, key_fingerprint);
        final_location
    }

    /// Places a known-novel entry at `location`, resizing first if the table is
    /// full or no candidate was found. Single-pass insert's placement tail.
    fn insert_at_location_after_resize_check(
        &mut self,
        location: Option<SlotLocation>,
        key_hash: u64,
        key: K,
        value: V,
        key_fingerprint: u8,
    ) -> Option<V> {
        let final_location = match location {
            Some(loc) if self.len < self.max_insertions => loc,
            _ => {
                let new_capacity = if self.total_slots == 0 {
                    INITIAL_CAPACITY
                } else {
                    self.total_slots.saturating_mul(2)
                };
                self.resize(new_capacity);
                self.choose_slot_for_new_key(key_hash)
                    .expect("no free slot found after resize")
            }
        };

        self.place_new_entry(final_location, key, value, key_fingerprint);
        None
    }

    /// Raw pointer to the whole slot at `loc`. Projects through raw pointers
    /// from shared `&Region` (level / special primary / special fallback),
    /// forming no intermediate `&mut`, so distinct locations yield
    /// non-aliasing `*mut`.
    ///
    /// # Safety
    /// `loc` must reference a live slot in this table.
    #[inline]
    unsafe fn slot_ptr_at(&self, loc: SlotLocation) -> *mut SlotEntry<K, V> {
        match loc {
            SlotLocation::Level {
                level_idx,
                slot_idx,
            } => {
                let levels_ptr: *const BucketLevel<SlotEntry<K, V>> = self.levels.as_ptr();
                // SAFETY: shared `&BucketLevel` only โ€” never `&mut` โ€” so no
                // aliasing tag.
                let level = unsafe { &*levels_ptr.add(level_idx) };
                level.slot_ptr(slot_idx)
            }
            SlotLocation::SpecialPrimary { slot_idx } => self.special.primary.slot_ptr(slot_idx),
            SlotLocation::SpecialFallback { slot_idx } => self.special.fallback.slot_ptr(slot_idx),
        }
    }

    /// Take the entry at `location` without updating counters or control bytes.
    ///
    /// # Safety
    /// `location` must reference a live, initialized occupied slot in this table.
    #[inline]
    unsafe fn take_entry_at(&mut self, location: SlotLocation) -> SlotEntry<K, V> {
        match location {
            SlotLocation::Level {
                level_idx,
                slot_idx,
            } => unsafe { self.levels[level_idx].take(slot_idx) },
            SlotLocation::SpecialPrimary { slot_idx } => unsafe {
                self.special.primary.take(slot_idx)
            },
            SlotLocation::SpecialFallback { slot_idx } => unsafe {
                self.special.fallback.take(slot_idx)
            },
        }
    }

    #[inline]
    fn erase_location(&mut self, location: SlotLocation) -> bool {
        match location {
            SlotLocation::Level {
                level_idx,
                slot_idx,
            } => self.levels[level_idx].erase(slot_idx),
            SlotLocation::SpecialPrimary { slot_idx } => self.special.primary.erase(slot_idx),
            SlotLocation::SpecialFallback { slot_idx } => self.special.fallback.erase(slot_idx),
        }
    }

    #[inline]
    fn account_erased_location(&mut self, location: SlotLocation, wrote_tombstone: bool) {
        match location {
            SlotLocation::Level { level_idx, .. } => {
                let level = &mut self.levels[level_idx];
                if wrote_tombstone {
                    level.tombstones += 1;
                }
                level.len -= 1;
            }
            SlotLocation::SpecialPrimary { .. } => {
                let primary = &mut self.special.primary;
                if wrote_tombstone {
                    primary.tombstones += 1;
                }
                primary.len -= 1;
                self.special.total_len -= 1;
            }
            SlotLocation::SpecialFallback { .. } => {
                let fallback = &mut self.special.fallback;
                if wrote_tombstone {
                    fallback.tombstones += 1;
                }
                fallback.len -= 1;
                self.special.total_len -= 1;
            }
        }
        self.len -= 1;
    }

    #[inline]
    fn finish_counted_removal(&mut self, location: SlotLocation) {
        let wrote_tombstone = self.erase_location(location);
        self.account_erased_location(location, wrote_tombstone);
    }

    /// Take + erase + decrement counters for the slot at `loc`. Shared by
    /// [`RawTable::remove`] and [`RawTable::extract_finish`]; the former adds a
    /// resize pass, the latter consolidates tombstones lazily.
    fn take_and_tombstone(&mut self, location: SlotLocation) -> (K, V) {
        // SAFETY: caller passes a live location found in this table.
        let removed = unsafe { self.take_entry_at(location) };
        self.finish_counted_removal(location);
        (removed.key, removed.value)
    }

    /// `true` if the region holding `loc` has accumulated enough tombstones
    /// that [`RawTable::remove`] should rehash in place.
    fn region_needs_cleanup(&self, location: SlotLocation) -> bool {
        let (tombstones, cap) = match location {
            SlotLocation::Level { level_idx, .. } => {
                let level = &self.levels[level_idx];
                (level.tombstones, level.capacity())
            }
            SlotLocation::SpecialPrimary { .. } => {
                let primary = &self.special.primary;
                (primary.tombstones, primary.capacity())
            }
            SlotLocation::SpecialFallback { .. } => {
                let fallback = &self.special.fallback;
                (fallback.tombstones, fallback.capacity())
            }
        };
        tombstones as usize > capacity::tombstone_cleanup_threshold(cap)
    }

    /// Bulk-clears all control bytes and zeroes counters. Called by
    /// [`map::Drain::drop`] after the slots' values have been taken.
    fn wipe_all(&mut self) {
        for level in &mut self.levels {
            level.clear_all_controls();
            level.len = 0;
            level.tombstones = 0;
        }
        self.special.primary.clear_all_controls();
        self.special.primary.len = 0;
        self.special.primary.tombstones = 0;
        self.special.fallback.clear_all_controls();
        self.special.fallback.len = 0;
        self.special.fallback.tombstones = 0;
        self.special.total_len = 0;
        self.len = 0;
        self.max_populated_level = 0;
    }

    /// Removes all entries, keeping allocated capacity.
    fn clear(&mut self) {
        for level in &mut self.levels {
            level.drop_values_and_clear();
            level.len = 0;
            level.tombstones = 0;
        }
        self.special.primary.drop_values_and_clear();
        self.special.primary.len = 0;
        self.special.primary.tombstones = 0;
        self.special.fallback.drop_values_and_clear();
        self.special.fallback.len = 0;
        self.special.fallback.tombstones = 0;
        self.special.total_len = 0;
        self.len = 0;
        self.max_populated_level = 0;
    }

    /// Fallible counterpart to [`Self::resize`]. Common path leaves `self`
    /// intact on `Err`; a failing 2x-retry allocation may empty `self`.
    fn try_resize(&mut self, new_capacity: usize) -> Result<(), TryReserveError>
    where
        S: Clone,
    {
        let mut target = new_capacity;
        let mut new_map = Self::try_with_slots_and_reserve_fraction_and_hasher_in(
            target,
            self.reserve_fraction,
            self.hash_builder.clone(),
            self.alloc.clone(),
        )?;

        let mut entries: Vec<(K, V)> = Vec::new();
        entries
            .try_reserve(self.len)
            .map_err(|_| TryReserveError::AllocError)?;
        self.drain_entries_into(&mut entries);

        let mut overflow: Vec<(K, V)> = Vec::new();
        loop {
            overflow.clear();
            for (k, v) in entries.drain(..) {
                if let Err(pair) = new_map.try_insert_new_entry_unchecked(k, v) {
                    overflow.push(pair);
                }
            }
            if overflow.is_empty() {
                *self = new_map;
                return Ok(());
            }
            new_map.drain_entries_into(&mut overflow);
            mem::swap(&mut entries, &mut overflow);
            target = target
                .checked_mul(2)
                .ok_or(TryReserveError::CapacityOverflow)?;
            new_map = Self::try_with_slots_and_reserve_fraction_and_hasher_in(
                target,
                self.reserve_fraction,
                self.hash_builder.clone(),
                self.alloc.clone(),
            )?;
        }
    }

    /// Internal fallible ctor for `try_resize`. `slots` is raw slot count
    /// (already inflated by the caller); public ctors take an insertion
    /// budget and inflate via `capacity_for` โ€” this one skips that.
    fn try_with_slots_and_reserve_fraction_and_hasher_in(
        total_slots: usize,
        reserve_fraction: f64,
        hash_builder: S,
        alloc: A,
    ) -> Result<Self, TryReserveError> {
        let reserve_fraction =
            capacity::sanitize_reserve_fraction(reserve_fraction).min(MAX_FUNNEL_RESERVE_FRACTION);
        let max_insertions = capacity::max_insertions(total_slots, reserve_fraction);

        let level_count = compute_level_count(reserve_fraction);
        let bucket_width = align::round_up_to_group(compute_bucket_width(reserve_fraction));
        let primary_probe_limit = probe::log_log_probe_limit(total_slots).max(1);

        let mut special_capacity =
            choose_special_capacity(total_slots, reserve_fraction, bucket_width);
        let mut main_capacity = total_slots.saturating_sub(special_capacity);
        let main_remainder = main_capacity % bucket_width.max(1);
        if main_remainder != 0 {
            main_capacity = main_capacity.saturating_sub(main_remainder);
            special_capacity = total_slots.saturating_sub(main_capacity);
        }

        let total_main_buckets = main_capacity.checked_div(bucket_width).unwrap_or(0);
        let level_bucket_counts = partition_funnel_buckets(total_main_buckets, level_count);
        let fallback_bucket_size = (primary_probe_limit.saturating_mul(2)).max(2);
        let primary_ctrl = align::round_up_to_pow2_groups(special_capacity.div_ceil(2));
        let fallback_ctrl =
            align::round_up_to_group(special_capacity.saturating_sub(special_capacity.div_ceil(2)));
        let (arena, levels, special) = FunnelGeometry::new(
            &level_bucket_counts,
            bucket_width,
            primary_ctrl,
            fallback_ctrl,
            fallback_bucket_size,
        )
        .try_alloc(&alloc)?;

        Ok(Self {
            levels,
            special,
            len: 0,
            total_slots,
            max_insertions,
            reserve_fraction,
            primary_probe_limit,
            max_populated_level: 0,
            hash_builder,
            alloc,
            arena,
        })
    }

    /// Rebuild in-place at `new_capacity`. Doubles `new_capacity` on
    /// insert overflow (funnel's structural failure mode under adversarial
    /// hashing) until every entry places.
    fn resize(&mut self, mut new_capacity: usize) {
        let mut entries: Vec<(K, V)> = Vec::with_capacity(self.len);
        self.drain_entries_into(&mut entries);
        let mut overflow: Vec<(K, V)> = Vec::new();
        loop {
            self.install_fresh_storage(new_capacity);
            overflow.clear();
            for (k, v) in entries.drain(..) {
                if let Err(pair) = self.try_insert_new_entry_unchecked(k, v) {
                    overflow.push(pair);
                }
            }
            if overflow.is_empty() {
                return;
            }
            self.drain_entries_into(&mut overflow);
            mem::swap(&mut entries, &mut overflow);
            new_capacity = new_capacity
                .checked_mul(2)
                .expect("capacity overflow during funnel resize retry");
        }
    }

    /// Move every live entry into `out`; ctrl bytes cleared so `install_fresh_storage`
    /// can free the old arena safely. Each ctrl is cleared *before* the move so
    /// a `Vec::push` realloc panic leaves no OCCUPIED slot behind to double-drop.
    fn drain_entries_into(&mut self, out: &mut Vec<(K, V)>) {
        for level in &mut self.levels {
            level.drain_values_and_clear(|entry| {
                out.push((entry.key, entry.value));
            });
        }
        self.special.drain_occupied_with(|entry| {
            out.push((entry.key, entry.value));
        });
        for level in &mut self.levels {
            level.len = 0;
            level.tombstones = 0;
        }
        self.special.primary.len = 0;
        self.special.primary.tombstones = 0;
        self.special.fallback.len = 0;
        self.special.fallback.tombstones = 0;
        self.special.total_len = 0;
        self.len = 0;
        self.max_populated_level = 0;
    }

    /// Replace `self`'s tables with empty storage sized for `new_capacity`.
    fn install_fresh_storage(&mut self, new_capacity: usize) {
        let level_count = compute_level_count(self.reserve_fraction);
        let bucket_width = align::round_up_to_group(compute_bucket_width(self.reserve_fraction));
        let mut special_capacity =
            choose_special_capacity(new_capacity, self.reserve_fraction, bucket_width);
        let mut main_capacity = new_capacity.saturating_sub(special_capacity);
        let main_remainder = main_capacity % bucket_width.max(1);
        if main_remainder != 0 {
            main_capacity = main_capacity.saturating_sub(main_remainder);
            special_capacity = new_capacity.saturating_sub(main_capacity);
        }
        let total_main_buckets = main_capacity.checked_div(bucket_width).unwrap_or(0);
        let level_bucket_counts = partition_funnel_buckets(total_main_buckets, level_count);
        let new_primary_probe_limit = probe::log_log_probe_limit(new_capacity).max(1);
        let fallback_bucket_size = (new_primary_probe_limit.saturating_mul(2)).max(2);
        let primary_raw = special_capacity.div_ceil(2);
        let fallback_raw = special_capacity.saturating_sub(primary_raw);
        let primary_ctrl = align::round_up_to_pow2_groups(primary_raw);
        let fallback_ctrl = align::round_up_to_group(fallback_raw);
        let alloc = &self.alloc;

        let (new_arena, new_levels, new_special) = FunnelGeometry::new(
            &level_bucket_counts,
            bucket_width,
            primary_ctrl,
            fallback_ctrl,
            fallback_bucket_size,
        )
        .alloc(alloc);

        // Drop old levels first (they read from old arena), then replace arena.
        let old_arena = mem::replace(&mut self.arena, new_arena);
        self.levels = new_levels;
        self.special = new_special;
        self.total_slots = new_capacity;
        self.max_insertions = capacity::max_insertions(new_capacity, self.reserve_fraction);
        self.primary_probe_limit = new_primary_probe_limit;
        self.max_populated_level = 0;

        // Free old arena (drain_entries_into already moved all values out).
        old_arena.deallocate(alloc);
    }

    #[inline]
    fn hash_key<Q>(&self, key: &Q) -> u64
    where
        Q: Hash + ?Sized,
    {
        self.hash_builder.hash_one(key)
    }

    /// Paper ยง5 insertion chain: attempt `L_1`, `L_2`, โ€ฆ, `L_ฮฑ` in order,
    /// stopping on the first level whose hashed bucket has a free slot;
    /// spill to `A_{ฮฑ+1}`.
    #[inline]
    fn choose_slot_for_new_key(&self, key_hash: u64) -> Option<SlotLocation> {
        for (level_idx, level) in self.levels.iter().enumerate() {
            if let Some(slot_idx) = level.first_free_in_bucket(key_hash) {
                return Some(SlotLocation::Level {
                    level_idx,
                    slot_idx,
                });
            }
        }

        if let Some(slot_idx) = self.first_free_in_special_primary(key_hash) {
            return Some(SlotLocation::SpecialPrimary { slot_idx });
        }

        self.first_free_in_special_fallback(key_hash)
            .map(|slot_idx| SlotLocation::SpecialFallback { slot_idx })
    }

    /// Probe primary then fallback for `key`. Pass `Some(candidate)` to also
    /// record the first free slot seen (for insert); `None` for lookup-only.
    #[cold]
    #[inline(never)]
    fn find_in_special<Q>(
        &self,
        key: &Q,
        key_hash: u64,
        key_fingerprint: u8,
        mut free_slot: FreeSlot,
    ) -> Option<SlotLocation>
    where
        Q: Equivalent<K> + ?Sized,
    {
        match self.find_in_special_primary(key_hash, key_fingerprint, key, free_slot.as_deref_mut())
        {
            LookupStep::Found(slot_idx) => {
                return Some(SlotLocation::SpecialPrimary { slot_idx });
            }
            LookupStep::StopSearch => return None,
            LookupStep::Continue => {}
        }
        self.find_in_special_fallback(key_hash, key_fingerprint, key, free_slot)
            .map(|slot_idx| SlotLocation::SpecialFallback { slot_idx })
    }

    /// Single-pass level probe. Returns the match if any; with `Some(free_slot)`
    /// records the first free slot so an insert places there without re-probing.
    /// The [`LevelMiss`] reports whether the chain ended clean (no special overflow).
    fn find_in_levels<Q>(
        &self,
        key: &Q,
        key_hash: u64,
        key_fingerprint: u8,
        free_slot: FreeSlot,
    ) -> (Option<SlotLocation>, LevelMiss)
    where
        Q: Equivalent<K> + ?Sized,
    {
        let wants_free = matches!(&free_slot, Some(out) if out.is_none());
        let mut local: Option<SlotLocation> = None;

        for (level_idx, level) in self.levels.iter().enumerate() {
            let mut slot_candidate: Option<usize> = None;
            let out = if wants_free && local.is_none() {
                Some(&mut slot_candidate)
            } else {
                None
            };
            let step = level.find_in_bucket(key_hash, key_fingerprint, key, out);
            if let Some(slot_idx) = slot_candidate {
                local = Some(SlotLocation::Level {
                    level_idx,
                    slot_idx,
                });
            }
            match step {
                LookupStep::Found(slot_idx) => {
                    return (
                        Some(SlotLocation::Level {
                            level_idx,
                            slot_idx,
                        }),
                        LevelMiss::MayContinue,
                    );
                }
                LookupStep::Continue => {}
                LookupStep::StopSearch => {
                    if let Some(out) = free_slot {
                        *out = local;
                    }
                    return (None, LevelMiss::ChainClean);
                }
            }
        }

        if wants_free && let Some(out) = free_slot {
            *out = local;
        }
        (None, LevelMiss::MayContinue)
    }

    #[inline]
    fn replace_existing_value(&mut self, location: SlotLocation, value: V) -> V {
        match location {
            SlotLocation::Level {
                level_idx,
                slot_idx,
            } => {
                let entry = unsafe { self.levels[level_idx].get_mut(slot_idx) };
                mem::replace(&mut entry.value, value)
            }
            SlotLocation::SpecialPrimary { slot_idx } => {
                let entry = unsafe { self.special.primary.get_mut(slot_idx) };
                mem::replace(&mut entry.value, value)
            }
            SlotLocation::SpecialFallback { slot_idx } => {
                let entry = unsafe { self.special.fallback.get_mut(slot_idx) };
                mem::replace(&mut entry.value, value)
            }
        }
    }

    /// Place a known-novel `key`/`value`. Returns `Err((key, value))` if no
    /// slot is available; the resize loop reclaims and retries at 2x.
    #[inline]
    fn try_insert_new_entry_unchecked(&mut self, key: K, value: V) -> Result<(), (K, V)> {
        let key_hash = self.hash_key(&key);
        let key_fingerprint = control::control_fingerprint(key_hash);
        let Some(location) = self.choose_slot_for_new_key(key_hash) else {
            return Err((key, value));
        };
        if let SlotLocation::Level {
            level_idx,
            slot_idx,
        } = location
        {
            self.place_new_level_entry(level_idx, slot_idx, key, value, key_fingerprint);
        } else {
            self.place_new_entry(location, key, value, key_fingerprint);
        }
        Ok(())
    }

    #[inline]
    fn place_new_entry(&mut self, location: SlotLocation, key: K, value: V, key_fingerprint: u8) {
        match location {
            SlotLocation::Level {
                level_idx,
                slot_idx,
            } => self.place_new_level_entry(level_idx, slot_idx, key, value, key_fingerprint),
            SlotLocation::SpecialPrimary { slot_idx } => {
                self.place_new_special_primary_entry(slot_idx, key, value, key_fingerprint);
            }
            SlotLocation::SpecialFallback { slot_idx } => {
                self.place_new_special_fallback_entry(slot_idx, key, value, key_fingerprint);
            }
        }
    }

    #[inline]
    fn place_new_level_entry(
        &mut self,
        level_idx: usize,
        slot_idx: usize,
        key: K,
        value: V,
        key_fingerprint: u8,
    ) {
        let level = &mut self.levels[level_idx];
        let was_tombstone = level.control_at(slot_idx) == CTRL_TOMBSTONE;
        level.write_with_control(slot_idx, SlotEntry { key, value }, key_fingerprint);
        level.len += 1;
        if was_tombstone {
            level.tombstones -= 1;
        }
        if level_idx > self.max_populated_level {
            self.max_populated_level = level_idx;
        }
        self.len += 1;
    }

    #[inline]
    fn place_new_special_primary_entry(
        &mut self,
        slot_idx: usize,
        key: K,
        value: V,
        key_fingerprint: u8,
    ) {
        let primary = &mut self.special.primary;
        // Reusing a tombstone slot must decrement the counter; otherwise
        // cleanup triggers on stale-since-resize counts.
        let was_tombstone = primary.control_at(slot_idx) == CTRL_TOMBSTONE;
        primary.write_with_control(slot_idx, SlotEntry { key, value }, key_fingerprint);
        primary.len += 1;
        if was_tombstone {
            primary.tombstones -= 1;
        }
        self.special.total_len += 1;
        self.len += 1;
    }

    #[inline]
    fn place_new_special_fallback_entry(
        &mut self,
        slot_idx: usize,
        key: K,
        value: V,
        key_fingerprint: u8,
    ) {
        let fallback = &mut self.special.fallback;
        fallback.write_with_control(slot_idx, SlotEntry { key, value }, key_fingerprint);
        fallback.len += 1;
        self.special.total_len += 1;
        self.len += 1;
    }

    fn first_free_in_special_primary(&self, key_hash: u64) -> Option<usize> {
        let primary = &self.special.primary;
        if primary.len as usize >= primary.capacity() {
            return None;
        }

        let group_count = primary.group_count();
        let group_limit = self.primary_probe_limit.min(group_count.max(1));
        let mask = primary.group_count_mask as usize;
        let mut probe = ProbeSeq::new(primary.group_start(key_hash), primary.group_step(key_hash));
        for _ in 0..group_limit {
            if let Some(slot_idx) = primary.first_free_in_group(probe.group) {
                return Some(slot_idx);
            }
            probe.advance(mask);
        }
        None
    }

    fn first_free_in_special_fallback(&self, key_hash: u64) -> Option<usize> {
        let fallback = &self.special.fallback;
        if fallback.len as usize >= fallback.capacity() {
            return None;
        }

        let bucket_a = fallback.bucket_a(key_hash);
        let bucket_b = fallback.bucket_b(key_hash);

        for &bucket_idx in &[bucket_a, bucket_b] {
            let range = fallback.bucket_range(bucket_idx);
            for slot_idx in range {
                if fallback.control_at(slot_idx).is_free() {
                    return Some(slot_idx);
                }
            }
        }

        None
    }

    /// Probe special primary for `key`. Bounded by `primary_probe_limit`
    /// groups; if reached without a match and no tombstones seen, returns
    /// `StopSearch` so the caller skips fallback. Pass `Some(out)` to
    /// record the first free `SlotLocation`; `None` for lookup-only.
    #[inline]
    fn find_in_special_primary<Q>(
        &self,
        key_hash: u64,
        key_fingerprint: u8,
        key: &Q,
        free_slot: FreeSlot,
    ) -> LookupStep
    where
        Q: Equivalent<K> + ?Sized,
    {
        let wants_free = matches!(&free_slot, Some(out) if out.is_none());
        let primary = &self.special.primary;

        if primary.capacity() == 0 || primary.len == 0 {
            if wants_free && let Some(out) = free_slot {
                *out = self
                    .first_free_in_special_primary(key_hash)
                    .map(|slot_idx| SlotLocation::SpecialPrimary { slot_idx });
            }
            return LookupStep::Continue;
        }

        let group_count = primary.group_count();
        let group_limit = self.primary_probe_limit.min(group_count.max(1));
        let mask = primary.group_count_mask as usize;
        let mut local: Option<usize> = None;
        let mut probe = ProbeSeq::new(primary.group_start(key_hash), primary.group_step(key_hash));

        let outcome: LookupStep = 'probe: {
            for _ in 0..group_limit {
                // Track free slots only when asked AND we don't already have
                // one. `first_free_in_group` doubles as the "any free?" check;
                // when not tracking we use the cheaper EMPTY-only mask.
                let has_free = if wants_free && local.is_none() {
                    let slot = primary.first_free_in_group(probe.group);
                    if let Some(s) = slot {
                        local = Some(s);
                    }
                    slot.is_some()
                } else {
                    primary.group_match_mask(probe.group, CTRL_EMPTY).any()
                };
                for relative_idx in primary.group_match_mask(probe.group, key_fingerprint) {
                    let slot_idx = probe.group * GROUP_SIZE + relative_idx;
                    let entry = unsafe { primary.get_ref(slot_idx) };
                    if key.equivalent(&entry.key) {
                        break 'probe LookupStep::Found(slot_idx);
                    }
                }
                // StopSearch: probe chain terminated naturally โ€” an EMPTY
                // slot in the group, with no TOMBSTONE that might be hiding
                // an overflow we'd need to chase.
                if has_free && !primary.group_match_mask(probe.group, CTRL_TOMBSTONE).any() {
                    break 'probe LookupStep::StopSearch;
                }
                probe.advance(mask);
            }
            LookupStep::Continue
        };

        if wants_free && let Some(out) = free_slot {
            *out = local.map(|slot_idx| SlotLocation::SpecialPrimary { slot_idx });
        }
        outcome
    }

    /// Probe special fallback for `key` across its two candidate buckets.
    #[inline]
    fn find_in_special_fallback<Q>(
        &self,
        key_hash: u64,
        key_fingerprint: u8,
        key: &Q,
        free_slot: FreeSlot,
    ) -> Option<usize>
    where
        Q: Equivalent<K> + ?Sized,
    {
        let wants_free = matches!(&free_slot, Some(out) if out.is_none());
        let fallback = &self.special.fallback;

        if fallback.capacity() == 0 || fallback.len == 0 {
            if wants_free && let Some(out) = free_slot {
                *out = self
                    .first_free_in_special_fallback(key_hash)
                    .map(|slot_idx| SlotLocation::SpecialFallback { slot_idx });
            }
            return None;
        }

        let bucket_a = fallback.bucket_a(key_hash);
        let bucket_b = fallback.bucket_b(key_hash);

        let mut local: Option<usize> = None;
        let mut found: Option<usize> = None;
        for bucket_idx in [bucket_a, bucket_b] {
            let need_match = found.is_none();
            let need_candidate = wants_free && local.is_none();
            if !need_match && !need_candidate {
                break;
            }
            let range = fallback.bucket_range(bucket_idx);
            if need_candidate {
                for slot_idx in range.clone() {
                    if fallback.control_at(slot_idx).is_free() {
                        local = Some(slot_idx);
                        break;
                    }
                }
            }
            if need_match {
                let controls = unsafe {
                    slice::from_raw_parts(fallback.ctrl_ptr().add(range.start), range.len())
                };
                let mut match_offset = 0;
                while let Some(relative_idx) = control::find_next_fingerprint_in_controls(
                    controls,
                    key_fingerprint,
                    match_offset,
                ) {
                    let slot_idx = range.start + relative_idx;
                    let entry = unsafe { fallback.get_ref(slot_idx) };
                    if key.equivalent(&entry.key) {
                        found = Some(slot_idx);
                        break;
                    }
                    match_offset = relative_idx + 1;
                }
            }
        }

        if wants_free && let Some(out) = free_slot {
            *out = local.map(|slot_idx| SlotLocation::SpecialFallback { slot_idx });
        }
        found
    }

    /// Dispatch `loc` to the right descriptor and return a shared reference
    /// to the slot. SAFETY: `loc` must reference an occupied slot.
    #[inline]
    unsafe fn slot_ref(&self, loc: SlotLocation) -> &SlotEntry<K, V> {
        match loc {
            SlotLocation::Level {
                level_idx,
                slot_idx,
            } => unsafe { self.levels[level_idx].get_ref(slot_idx) },
            SlotLocation::SpecialPrimary { slot_idx } => unsafe {
                self.special.primary.get_ref(slot_idx)
            },
            SlotLocation::SpecialFallback { slot_idx } => unsafe {
                self.special.fallback.get_ref(slot_idx)
            },
        }
    }

    #[inline]
    fn find_slot_location_with_hash<Q>(
        &self,
        key: &Q,
        key_hash: u64,
        key_fingerprint: u8,
    ) -> Option<SlotLocation>
    where
        Q: Equivalent<K> + ?Sized,
    {
        // SAFETY: `levels.len() == level_count >= 1` (fixed at construction), so
        // index 0 is always valid. Elides the hot-path bounds check + panic pad.
        let level0 = unsafe { self.levels.get_unchecked(0) };
        match level0.find_in_bucket(key_hash, key_fingerprint, key, None) {
            LookupStep::Found(slot_idx) => {
                return Some(SlotLocation::Level {
                    level_idx: 0,
                    slot_idx,
                });
            }
            LookupStep::Continue => {}
            LookupStep::StopSearch => return None,
        }

        if self.max_populated_level > 0 {
            let search_limit = (self.max_populated_level + 1).min(self.levels.len());
            // SAFETY: `search_limit <= levels.len()` by the `min` above, and
            // `1 <= search_limit` whenever `max_populated_level > 0`, so the
            // range is in bounds. Elides the slice bounds check.
            let tail = unsafe { self.levels.get_unchecked(1..search_limit) };
            for (offset, level) in tail.iter().enumerate() {
                match level.find_in_bucket(key_hash, key_fingerprint, key, None) {
                    LookupStep::Found(slot_idx) => {
                        return Some(SlotLocation::Level {
                            level_idx: offset + 1,
                            slot_idx,
                        });
                    }
                    LookupStep::Continue => {}
                    LookupStep::StopSearch => return None,
                }
            }
        }

        // Special tables are only populated under overflow.
        if self.special.total_len == 0 {
            return None;
        }
        self.find_in_special(key, key_hash, key_fingerprint, None)
    }

    fn shrink_max_populated_level(&mut self) {
        while self.max_populated_level > 0 && self.levels[self.max_populated_level].len == 0 {
            self.max_populated_level -= 1;
        }
    }
}

impl<K, V, S, A> FunnelTable<K, V, S, A>
where
    K: Eq + Hash,
    S: BuildHasher,
    A: Allocator + Clone,
{
    /// Cold path of [`RawTable::scan_next`]: first-call region prime and region
    /// crossings (levels โ†’ special primary โ†’ fallback). Kept out of line so the
    /// per-element hot path inlines.
    #[cold]
    fn scan_advance(&self, scan: &mut FunnelScan) -> Option<(*mut SlotEntry<K, V>, SlotLocation)> {
        if !scan.region.started() {
            // Prime the cursor on the first region. With no levels, jump
            // straight to the special primary.
            if self.levels.is_empty() {
                scan.phase = ScanPhase::Primary;
                scan.region.enter(&self.special.primary);
            } else {
                scan.region.enter(&self.levels[0]);
            }
        }
        loop {
            if let Some((ptr, slot_idx)) = scan.region.step::<SlotEntry<K, V>>() {
                return Some((ptr, scan.location_at(slot_idx)));
            }
            // Current region exhausted: advance, re-deriving the region pointer
            // from `&self`.
            match scan.phase {
                ScanPhase::Levels => {
                    scan.level_idx += 1;
                    if scan.level_idx < self.levels.len() {
                        scan.region.enter(&self.levels[scan.level_idx]);
                    } else {
                        scan.phase = ScanPhase::Primary;
                        scan.region.enter(&self.special.primary);
                    }
                }
                ScanPhase::Primary => {
                    scan.phase = ScanPhase::Fallback;
                    scan.region.enter(&self.special.fallback);
                }
                ScanPhase::Fallback => {
                    scan.phase = ScanPhase::Done;
                    return None;
                }
                ScanPhase::Done => return None,
            }
        }
    }
}

// `SlotEntry` is `pub(crate)`; the `RawTable` trait (in the private `map`
// module) exposes it in `slot_ref`/`slot_ptr`, so the impl mirrors the trait's
// private-interface lint exemption.
#[allow(private_interfaces)]
impl<K, V, S, A> RawTable<K, V> for FunnelTable<K, V, S, A>
where
    K: Eq + Hash,
    S: BuildHasher,
    A: Allocator + Clone,
{
    type Location = SlotLocation;
    type Hasher = S;
    type Alloc = A;
    type Scan = FunnelScan;

    #[inline]
    fn with_capacity_and_reserve_fraction_and_hasher_in(
        capacity: usize,
        reserve_fraction: f64,
        hash_builder: S,
        alloc: A,
    ) -> Self {
        Self::with_capacity_and_reserve_fraction_and_hasher_in(
            capacity,
            reserve_fraction,
            hash_builder,
            alloc,
        )
    }

    #[inline]
    fn hasher(&self) -> &S {
        &self.hash_builder
    }

    #[inline]
    fn allocator(&self) -> &A {
        &self.alloc
    }

    #[inline]
    fn len(&self) -> usize {
        self.len
    }

    #[inline]
    fn capacity(&self) -> usize {
        self.max_insertions
    }

    #[inline]
    fn total_slots(&self) -> usize {
        self.total_slots
    }

    #[inline]
    fn reserve_fraction(&self) -> f64 {
        self.reserve_fraction
    }

    #[inline]
    fn grow_capacity_for(&self, needed: usize) -> Option<usize> {
        self.grow_capacity_for(needed)
    }

    #[inline]
    fn resize(&mut self, new_capacity: usize) {
        self.resize(new_capacity);
    }

    #[inline]
    fn try_resize(&mut self, new_capacity: usize) -> Result<(), TryReserveError>
    where
        S: Clone,
    {
        self.try_resize(new_capacity)
    }

    #[inline]
    fn clear(&mut self) {
        self.clear();
    }

    #[inline]
    fn find<Q>(&self, key: &Q, hash: u64, fingerprint: u8) -> Option<SlotLocation>
    where
        Q: Hash + Equivalent<K> + ?Sized,
    {
        self.find_slot_location_with_hash(key, hash, fingerprint)
    }

    #[inline]
    unsafe fn slot_ref(&self, loc: SlotLocation) -> &SlotEntry<K, V> {
        unsafe { self.slot_ref(loc) }
    }

    #[inline]
    unsafe fn slot_ptr(&self, loc: SlotLocation) -> *mut SlotEntry<K, V> {
        unsafe { self.slot_ptr_at(loc) }
    }

    #[inline]
    fn replace_value(&mut self, loc: SlotLocation, value: V) -> V {
        self.replace_existing_value(loc, value)
    }

    #[inline]
    fn insert_for_vacant(&mut self, key: K, value: V, hash: u64) -> SlotLocation {
        self.insert_for_vacant_entry(key, value, hash)
    }

    fn insert(&mut self, key: K, value: V, key_hash: u64) -> Option<V>
    where
        K: Hash + Eq,
    {
        let key_fingerprint = control::control_fingerprint(key_hash);

        // One pass over levels: on match replace; on miss keep the first free
        // slot as the insertion candidate.
        let mut candidate: Option<SlotLocation> = None;
        let (found, miss) =
            self.find_in_levels(&key, key_hash, key_fingerprint, Some(&mut candidate));
        if let Some(location) = found {
            return Some(self.replace_existing_value(location, value));
        }

        // Skip the special-array dedup when the chain ended clean (no overflow
        // possible) or special is empty โ€” place at the level candidate.
        if (matches!(miss, LevelMiss::ChainClean) || self.special.total_len == 0)
            && let Some(SlotLocation::Level {
                level_idx,
                slot_idx,
            }) = candidate
        {
            if self.len < self.max_insertions {
                self.place_new_level_entry(level_idx, slot_idx, key, value, key_fingerprint);
                return None;
            }
            return self.insert_at_location_after_resize_check(
                candidate,
                key_hash,
                key,
                value,
                key_fingerprint,
            );
        }

        // Cold: key may have overflowed to special; probe it for a match.
        if let Some(location) =
            self.find_in_special(&key, key_hash, key_fingerprint, Some(&mut candidate))
        {
            return Some(self.replace_existing_value(location, value));
        }

        self.insert_at_location_after_resize_check(candidate, key_hash, key, value, key_fingerprint)
    }

    fn remove(&mut self, loc: SlotLocation) -> (K, V) {
        let kv = self.take_and_tombstone(loc);
        self.shrink_max_populated_level();
        if self.region_needs_cleanup(loc) {
            self.resize(self.total_slots);
        }
        kv
    }

    #[inline]
    fn tombstone_slot(&mut self, location: SlotLocation) {
        self.erase_location(location);
    }

    #[inline]
    fn extract_finish(&mut self, location: SlotLocation) {
        self.finish_counted_removal(location);
    }

    #[inline]
    fn scan(&self) -> FunnelScan {
        FunnelScan {
            phase: ScanPhase::Levels,
            level_idx: 0,
            region: RegionCursor::new(),
        }
    }

    #[inline]
    fn scan_next(&self, scan: &mut FunnelScan) -> Option<(*mut SlotEntry<K, V>, SlotLocation)> {
        // Hot path: another occupied slot in the region the cursor already holds.
        if scan.region.started()
            && let Some((ptr, slot_idx)) = scan.region.step::<SlotEntry<K, V>>()
        {
            return Some((ptr, scan.location_at(slot_idx)));
        }
        self.scan_advance(scan)
    }

    fn wipe_all(&mut self) {
        self.wipe_all();
    }

    fn clone_table(&self) -> Self
    where
        K: Clone,
        V: Clone,
        S: Clone,
    {
        self.clone_storage()
    }
}

/// Three-phase region of a [`FunnelScan`]: walk all bucket levels, then the
/// special primary, then the special fallback.
#[derive(Clone, Copy)]
enum ScanPhase {
    Levels,
    Primary,
    Fallback,
    Done,
}

/// Pointerless multi-region scan cursor for [`RawTable::scan`]. Holds only the
/// current phase + level index + a shared [`RegionCursor`]; the owning iterator
/// can move the table because no pointer into it is stored across calls.
/// Mirrors [`crate::elastic::ElasticScan`] but crosses three region kinds
/// (levels โ†’ special primary โ†’ special fallback).
#[derive(Clone)]
pub struct FunnelScan {
    phase: ScanPhase,
    level_idx: usize,
    region: RegionCursor,
}

impl FunnelScan {
    /// Maps `slot_idx` in the cursor's current region to its [`SlotLocation`].
    /// Shared by the hot and cold `scan_next` paths.
    #[inline]
    fn location_at(&self, slot_idx: usize) -> SlotLocation {
        match self.phase {
            ScanPhase::Levels => SlotLocation::Level {
                level_idx: self.level_idx,
                slot_idx,
            },
            ScanPhase::Primary => SlotLocation::SpecialPrimary { slot_idx },
            ScanPhase::Fallback => SlotLocation::SpecialFallback { slot_idx },
            // `step` returns `None` on an empty region, so the cursor never
            // yields once the phase machine reaches `Done`.
            ScanPhase::Done => unreachable!("cursor empty in Done phase"),
        }
    }
}

/// Paper ยง5: `ฮฑ = โŒˆ4 log ฮดโปยน + 10โŒ‰` levels (excluding the special array).
fn compute_level_count(reserve_fraction: f64) -> usize {
    cast::ceil_to_usize((4.0 * (1.0 / reserve_fraction).log2() + 10.0).max(1.0))
}

/// Paper ยง5: `ฮฒ = โŒˆ2 log ฮดโปยนโŒ‰` slots per bucket A_{i,j}.
fn compute_bucket_width(reserve_fraction: f64) -> usize {
    cast::ceil_to_usize((2.0 * (1.0 / reserve_fraction).log2()).max(1.0))
}

/// Paper ยง5: `โŒˆฮดn/2โŒ‰ โ‰ค |A_{ฮฑ+1}| โ‰ค โŒŠ3ฮดn/4โŒ‹`, with the main capacity
/// constrained to a multiple of `ฮฒ` so each level is `ฮฒยทa_i` slots.
fn choose_special_capacity(
    total_capacity: usize,
    reserve_fraction: f64,
    bucket_size: usize,
) -> usize {
    if total_capacity == 0 {
        return 0;
    }

    let total_capacity_f64 = cast::usize_to_f64(total_capacity);
    let lower_bound = cast::ceil_to_usize((reserve_fraction * total_capacity_f64) / 2.0);
    let upper_bound = cast::floor_to_usize((3.0 * reserve_fraction * total_capacity_f64) / 4.0);
    let lower_bound = lower_bound.min(total_capacity);
    let upper_bound = upper_bound.min(total_capacity);

    if lower_bound <= upper_bound {
        for special_capacity in (lower_bound..=upper_bound).rev() {
            if (total_capacity - special_capacity).is_multiple_of(bucket_size.max(1)) {
                return special_capacity;
            }
        }
    }

    let target = cast::round_to_usize(
        ((5.0 * reserve_fraction * total_capacity_f64) / 8.0).clamp(0.0, total_capacity_f64),
    );

    let mut best_special_capacity = total_capacity % bucket_size.max(1);
    let mut best_distance = usize::MAX;

    for main_capacity in (0..=total_capacity).step_by(bucket_size.max(1)) {
        let special_capacity = total_capacity - main_capacity;
        let distance = special_capacity.abs_diff(target);
        if distance < best_distance {
            best_distance = distance;
            best_special_capacity = special_capacity;
        }
    }

    // Paper ยง5: A_{ฮฑ+1} must be non-empty. Floor at one bucket so the
    // cascade always has a final landing spot.
    if best_special_capacity == 0 {
        best_special_capacity = bucket_size.min(total_capacity);
    }
    best_special_capacity
}

/// Paper ยง5: split `ฮฑ` levels with `a_{i+1} = 3a_i/4 ยฑ 1`, geometrically decreasing.
/// Output is monotone non-increasing so `L0` is always the largest.
fn partition_funnel_buckets(total_buckets: usize, level_count: usize) -> Vec<usize> {
    if level_count == 0 {
        return Vec::new();
    }

    if total_buckets == 0 {
        return vec![0; level_count];
    }

    let first_level_guess = {
        let ratio = 0.75f64;
        let denom = 1.0 - ratio.powi(i32::try_from(level_count).expect("level count fits in i32"));
        if denom <= 0.0 {
            total_buckets.max(1)
        } else {
            cast::round_to_usize(
                (((cast::usize_to_f64(total_buckets)) * (1.0 - ratio)) / denom).max(0.0),
            )
        }
    };

    // The closed-form guess may be off by a few buckets โ€” its sum doesn't
    // always hit `total_buckets` exactly under integer rounding. Search
    // outward by `radius` until a valid sequence is found.
    //
    // Worst case `O(total_buckets ยท level_count)`; in practice `radius`
    // stays at a small constant.
    for radius in 0..=total_buckets {
        let lower = first_level_guess.saturating_sub(radius);
        if let Some(bucket_counts) = build_funnel_bucket_sequence(total_buckets, level_count, lower)
        {
            return bucket_counts;
        }

        let upper = first_level_guess.saturating_add(radius).min(total_buckets);
        if upper != lower
            && let Some(bucket_counts) =
                build_funnel_bucket_sequence(total_buckets, level_count, upper)
        {
            return bucket_counts;
        }
    }

    let mut fallback_counts = vec![0; level_count];
    fallback_counts[0] = total_buckets;
    fallback_counts
}

fn build_funnel_bucket_sequence(
    total_buckets: usize,
    level_count: usize,
    first_level_bucket_count: usize,
) -> Option<Vec<usize>> {
    if level_count == 0 || first_level_bucket_count > total_buckets {
        return None;
    }

    let mut bucket_counts = Vec::with_capacity(level_count);
    bucket_counts.push(first_level_bucket_count);
    let mut remaining = total_buckets.saturating_sub(first_level_bucket_count);
    let mut previous_bucket_count = first_level_bucket_count;

    for level_idx in 1..level_count {
        let levels_after = level_count - level_idx - 1;
        let (min_next_bucket_count, max_next_bucket_count) =
            next_bucket_count_bounds(previous_bucket_count);
        let ideal_next_bucket_count = ((3 * previous_bucket_count + 2) / 4)
            .clamp(min_next_bucket_count, max_next_bucket_count);

        let mut chosen_bucket_count = None;
        let mut best_distance = usize::MAX;
        let candidate_upper_bound = max_next_bucket_count.min(remaining);
        for candidate_bucket_count in min_next_bucket_count..=candidate_upper_bound {
            let remaining_after_candidate = remaining - candidate_bucket_count;
            let (tail_min_sum, tail_max_sum) =
                possible_tail_sum_range(candidate_bucket_count, levels_after);
            if remaining_after_candidate < tail_min_sum || remaining_after_candidate > tail_max_sum
            {
                continue;
            }

            let distance = candidate_bucket_count.abs_diff(ideal_next_bucket_count);
            if distance < best_distance {
                best_distance = distance;
                chosen_bucket_count = Some(candidate_bucket_count);
                if distance == 0 {
                    break;
                }
            }
        }
        let chosen_bucket_count = chosen_bucket_count?;

        bucket_counts.push(chosen_bucket_count);
        remaining -= chosen_bucket_count;
        previous_bucket_count = chosen_bucket_count;
    }

    if remaining == 0 {
        Some(bucket_counts)
    } else {
        None
    }
}

fn next_bucket_count_bounds(current_bucket_count: usize) -> (usize, usize) {
    let scaled = current_bucket_count.saturating_mul(3);
    let min_next_bucket_count = scaled.saturating_sub(4).div_ceil(4);
    let max_next_bucket_count = (scaled.saturating_add(4) / 4).min(current_bucket_count);
    (
        min_next_bucket_count,
        max_next_bucket_count.max(min_next_bucket_count),
    )
}

fn possible_tail_sum_range(start_bucket_count: usize, levels_after: usize) -> (usize, usize) {
    let mut min_sum = 0;
    let mut max_sum = 0;
    let mut min_previous = start_bucket_count;
    let mut max_previous = start_bucket_count;

    for _ in 0..levels_after {
        let (next_min, _) = next_bucket_count_bounds(min_previous);
        let (_, next_max) = next_bucket_count_bounds(max_previous);
        min_sum += next_min;
        max_sum += next_max;
        min_previous = next_min;
        max_previous = next_max;
    }

    (min_sum, max_sum)
}

impl<K, V, S, A> FunnelTable<K, V, S, A>
where
    K: Clone,
    V: Clone,
    S: Clone,
    A: Allocator + Clone,
{
    /// Deep-clones storage + hasher + allocator. Backs the
    /// [`RawTable::clone_table`] impl; the [`map::HashMap`] shell provides the
    /// public [`Clone`].
    fn clone_storage(&self) -> Self {
        // Build level_bucket_counts from existing level descriptors.
        let bucket_width = align::round_up_to_group(compute_bucket_width(self.reserve_fraction));
        let primary_ctrl = self.special.primary.capacity as usize;
        let fallback_ctrl = self.special.fallback.capacity as usize;
        let level_bucket_counts: Vec<usize> = self
            .levels
            .iter()
            .map(|l| {
                if l.bucket_count_mask == 0 && l.capacity == 0 {
                    0
                } else {
                    l.bucket_count_mask as usize + 1
                }
            })
            .collect();
        let fallback_bucket_size = (self.primary_probe_limit.saturating_mul(2)).max(2);

        let (arena, levels, special) = FunnelGeometry::new(
            &level_bucket_counts,
            bucket_width,
            primary_ctrl,
            fallback_ctrl,
            fallback_bucket_size,
        )
        .alloc(&self.alloc);

        // Drop guard: if a user-provided `Clone` impl panics inside
        // [`clone_region_panic_safe`], walk every region's OCCUPIED ctrls to
        // drop already-cloned values, then deallocate the partially-built arena.
        // `Arena` has no `Drop`, so without this the entire arena
        // allocation would leak on unwind.
        let mut guard = arena::ArenaDropGuard::new(
            arena,
            FunnelRegions { levels, special },
            self.alloc.clone(),
        );
        // Panic-safe order: clone value, write slot, then ctrl byte. If a
        // clone panics, only initialized slots carry OCCUPIED ctrls โ€” the
        // guard's `drop_values` walks exactly those.
        for (dst, src_lvl) in guard
            .regions_mut()
            .levels
            .iter_mut()
            .zip(self.levels.iter())
        {
            arena::clone_region_panic_safe::<K, V>(
                src_lvl.ctrl_ptr,
                dst.ctrl_ptr,
                src_lvl.data_ptr,
                dst.data_ptr,
                src_lvl.capacity as usize,
            );
            dst.len = src_lvl.len;
            dst.tombstones = src_lvl.tombstones;
        }

        let special_mut = &mut guard.regions_mut().special;
        {
            let s = &self.special.primary;
            let d = &mut special_mut.primary;
            arena::clone_region_panic_safe::<K, V>(
                s.ctrl_ptr,
                d.ctrl_ptr,
                s.data_ptr,
                d.data_ptr,
                s.capacity as usize,
            );
            d.len = s.len;
            d.tombstones = s.tombstones;
        }

        {
            let s = &self.special.fallback;
            let d = &mut special_mut.fallback;
            arena::clone_region_panic_safe::<K, V>(
                s.ctrl_ptr,
                d.ctrl_ptr,
                s.data_ptr,
                d.data_ptr,
                s.capacity as usize,
            );
            d.len = s.len;
            d.tombstones = s.tombstones;
        }

        special_mut.total_len = self.special.total_len;

        // Success: reclaim arena + regions so the guard's Drop no-ops.
        let (arena, FunnelRegions { levels, special }) = guard.disarm();

        Self {
            levels,
            special,
            len: self.len,
            total_slots: self.total_slots,
            max_insertions: self.max_insertions,
            reserve_fraction: self.reserve_fraction,
            primary_probe_limit: self.primary_probe_limit,
            max_populated_level: self.max_populated_level,
            hash_builder: self.hash_builder.clone(),
            alloc: self.alloc.clone(),
            arena,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::hash::{BuildHasher, Hasher};

    #[test]
    fn funnel_layout_covers_capacity() {
        // `with_capacity(n)` interprets `n` as the insertion budget. Internal
        // slot allocation rounds up so `capacity() >= n` and total slots
        // (level + special) cover that budget.
        let requested = 257;
        let map: FunnelHashMap<i32, i32> = FunnelHashMap::with_capacity(requested);
        assert!(
            map.capacity() >= requested,
            "capacity={} below requested={requested}",
            map.capacity()
        );
        let table = map.table();
        let level_capacity: usize = table.levels.iter().map(BucketLevel::capacity).sum();
        let special_capacity = table.special.primary.capacity() + table.special.fallback.capacity();
        let total = level_capacity + special_capacity;
        assert!(
            total >= requested,
            "total={total} below requested={requested}"
        );
    }

    #[test]
    fn partition_buckets_monotone_paper_invariant() {
        // Paper: A_i are "geometrically decreasing in size" (a_{i+1} = 3a_i/4 ยฑ 1).
        // Concretely, partition output must be monotone non-increasing so that
        // L0 is always largest (highest hit rate, shortest insert chain).
        for total in 0usize..=64 {
            for levels in 1usize..=24 {
                let p = partition_funnel_buckets(total, levels);
                assert_eq!(p.len(), levels, "len mismatch for ({total}, {levels})");
                assert_eq!(
                    p.iter().sum::<usize>(),
                    total,
                    "sum for ({total}, {levels})"
                );
                for w in p.windows(2) {
                    assert!(w[1] <= w[0], "non-monotone for ({total}, {levels}): {p:?}");
                }
            }
        }
    }

    #[test]
    fn special_primary_single_group_edge_case() {
        // Smallest capacity exercises the SpecialPrimary path with
        // `group_count == 1` (`mask == 0`). The odd-step probe must still
        // make forward progress (loop terminates via `group_limit`).
        let mut map: FunnelHashMap<u64, u64> = FunnelHashMap::with_capacity(1);
        assert_eq!(
            map.table().special.primary.group_count_mask,
            0,
            "regression assumes a single-group special primary"
        );
        for i in 0..16 {
            map.insert(i, i * 3);
        }
        for i in 0..16 {
            assert_eq!(map.get(&i), Some(&(i * 3)));
        }
        for i in 0..8 {
            assert_eq!(map.remove(&i), Some(i * 3));
        }
        for i in 0..8 {
            assert_eq!(map.get(&i), None);
        }
        for i in 8..16 {
            assert_eq!(map.get(&i), Some(&(i * 3)));
        }
    }

    #[test]
    fn clear_then_reinsert_preserves_level_entries() {
        let mut map: FunnelHashMap<u64, u64> = FunnelHashMap::with_capacity(512);
        for i in 0..384 {
            map.insert(i, i ^ 0xa5a5);
        }
        map.clear();

        for i in 512..896 {
            map.insert(i, i ^ 0x5a5a);
        }

        assert_eq!(map.len(), 384);
        assert_eq!(map.table().special.total_len, 0);
        for i in 512..896 {
            assert_eq!(map.get(&i), Some(&(i ^ 0x5a5a)));
        }
    }

    #[test]
    fn level_tombstone_reuse_decrements_counter() {
        struct ConstHasher;
        impl Hasher for ConstHasher {
            fn finish(&self) -> u64 {
                0
            }
            fn write(&mut self, _: &[u8]) {}
        }
        struct ConstHashBuilder;
        impl BuildHasher for ConstHashBuilder {
            type Hasher = ConstHasher;
            fn build_hasher(&self) -> Self::Hasher {
                ConstHasher
            }
        }

        let mut map: FunnelHashMap<i32, i32, ConstHashBuilder> =
            FunnelHashMap::with_capacity_and_reserve_fraction_and_hasher_in(
                2048,
                crate::common::config::DEFAULT_RESERVE_FRACTION,
                ConstHashBuilder,
                Global,
            );

        let l0_bucket_size = 1usize << map.table().levels[0].bucket_size_log2;
        for i in 0..i32::try_from(l0_bucket_size).unwrap() {
            map.insert(i, i);
        }
        assert_eq!(map.table().levels[0].tombstones, 0);

        assert_eq!(map.remove(&0), Some(0));
        assert_eq!(map.table().levels[0].tombstones, 1);

        map.insert(10_000, 10_000);
        assert_eq!(map.table().levels[0].tombstones, 0);
        assert_eq!(map.table().levels[0].len as usize, l0_bucket_size);
        assert_eq!(map.get(&10_000), Some(&10_000));
    }

    #[test]
    #[cfg_attr(miri, ignore)] // FIXME: takes too long
    fn delete_insert_cycles_trigger_rebuild() {
        // Exercises the tombstone cleanup path: 6000 remove+insert cycles
        // on a 12K map forces level.tombstones > capacity/2.
        let n = 12_000;
        let mut map = FunnelHashMap::with_capacity(n * 2);
        for i in 0..n {
            map.insert(i, i);
        }

        for i in 0..6000 {
            assert!(map.remove(&i).is_some(), "remove {i} failed");
            map.insert(i + n, i + n);
        }

        assert_eq!(map.len(), n);
        // Verify all remaining keys are findable.
        for i in 6000..n {
            assert_eq!(map.get(&i), Some(&i), "original key {i} missing");
        }
        for i in 0..6000 {
            assert_eq!(
                map.get(&(i + n)),
                Some(&(i + n)),
                "new key {} missing",
                i + n
            );
        }
    }

    #[test]
    fn retain_does_not_trigger_mid_iter_resize_with_clustered_tombstones() {
        // `retain` cleans up only on iterator Drop, at the same capacity โ€”
        // slot count must not change.
        let mut map: FunnelHashMap<i32, i32> = FunnelHashMap::with_capacity(1024);
        let max = i32::try_from(capacity::max_insertions(
            map.capacity(),
            crate::common::config::DEFAULT_RESERVE_FRACTION,
        ))
        .expect("test capacity fits i32");
        for i in 0..max {
            map.insert(i, i);
        }
        let initial_capacity = map.capacity();
        map.retain(|k, _| k % 2 == 0);

        let expected_count = (0..max).filter(|i| i % 2 == 0).count();
        assert_eq!(map.len(), expected_count);
        for i in 0..max {
            if i % 2 == 0 {
                assert_eq!(map.get(&i), Some(&i), "kept key {i} missing");
            } else {
                assert!(map.get(&i).is_none(), "dropped key {i} survived");
            }
        }
        assert_eq!(
            map.capacity(),
            initial_capacity,
            "retain must not change the slot count, only rehash in place"
        );
    }

    #[test]
    fn bucket_overflow_promotes_max_populated_level() {
        // Paper ยง5: A_{i,j} overflow must spill into A_{i+1}, not skip to the
        // special array. Constant hasher pins every key to the same L0 bucket.
        struct ConstHasher;
        impl Hasher for ConstHasher {
            fn finish(&self) -> u64 {
                0
            }
            fn write(&mut self, _: &[u8]) {}
        }
        struct ConstHashBuilder;
        impl BuildHasher for ConstHashBuilder {
            type Hasher = ConstHasher;
            fn build_hasher(&self) -> Self::Hasher {
                ConstHasher
            }
        }

        let mut map: FunnelHashMap<i32, i32, ConstHashBuilder> =
            FunnelHashMap::with_capacity_and_reserve_fraction_and_hasher_in(
                2048,
                crate::common::config::DEFAULT_RESERVE_FRACTION,
                ConstHashBuilder,
                Global,
            );
        assert!(
            map.table().levels.len() > 1,
            "test requires multi-level layout"
        );
        let l0_bucket_size =
            i32::try_from(1usize << map.table().levels[0].bucket_size_log2).unwrap();
        // bucket holds at most l0_bucket_size; one more forces a spill.
        for i in 0..=l0_bucket_size {
            map.insert(i, i);
        }
        assert_eq!(
            map.table().max_populated_level,
            1,
            "first bucket overflow should land in A_1, not the special array"
        );
        for i in 0..=l0_bucket_size {
            assert_eq!(map.get(&i), Some(&i));
        }
    }

    #[test]
    fn special_array_removal_updates_region_counts_once() {
        struct ConstHasher;
        impl Hasher for ConstHasher {
            fn finish(&self) -> u64 {
                0
            }
            fn write(&mut self, _: &[u8]) {}
        }
        struct ConstHashBuilder;
        impl BuildHasher for ConstHashBuilder {
            type Hasher = ConstHasher;
            fn build_hasher(&self) -> Self::Hasher {
                ConstHasher
            }
        }

        let mut map: FunnelHashMap<i32, i32, ConstHashBuilder> =
            FunnelHashMap::with_capacity_and_reserve_fraction_and_hasher_in(
                2048,
                crate::common::config::DEFAULT_RESERVE_FRACTION,
                ConstHashBuilder,
                Global,
            );
        let mut inserted = 0i32;
        let max_insertions = i32::try_from(map.capacity()).expect("test capacity fits i32");
        while map.table().special.total_len == 0 && inserted < max_insertions {
            map.insert(inserted, inserted);
            inserted += 1;
        }
        assert!(
            map.table().special.total_len > 0,
            "test requires at least one special-array entry"
        );

        let fingerprint = control::control_fingerprint(0);
        let special_key = (0..inserted)
            .find(|key| {
                matches!(
                    map.table()
                        .find_slot_location_with_hash(key, 0, fingerprint),
                    Some(
                        SlotLocation::SpecialPrimary { .. } | SlotLocation::SpecialFallback { .. }
                    )
                )
            })
            .expect("inserted special entry must be findable");

        let before_special = map.table().special.total_len;
        let before_len = map.len();
        assert_eq!(map.remove(&special_key), Some(special_key));
        assert_eq!(map.table().special.total_len, before_special - 1);
        assert_eq!(map.len(), before_len - 1);
    }

    #[test]
    fn reserve_fraction_clamped_to_funnel_max() {
        // Funnel's correctness proof requires reserve_fraction <= 1/8.
        let map: FunnelHashMap<i32, i32> =
            FunnelHashMap::with_capacity_and_reserve_fraction(256, 0.5);
        assert!(
            map.table().reserve_fraction <= MAX_FUNNEL_RESERVE_FRACTION,
            "reserve_fraction={} not clamped to {MAX_FUNNEL_RESERVE_FRACTION}",
            map.table().reserve_fraction
        );
    }
}