llvm-native-core 0.1.6

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
// tool_xxhash.rs — Clean-room native Rust reimplementation of xxHash family (github.com/Cyan4973/xxHash, 9K+ stars)
//
// This module provides standalone, no-std-compatible implementations of all xxHash
// algorithm variants: XXH32, XXH64, XXH3_64, and XXH3_128.  Every function uses
// only core/std primitives — no external crates, no unsafe, no C FFI.
//
// The xxHash family is designed by Yann Collet and released under the BSD-2-Clause
// license.  This file is a clean-room reimplementation written from the published
// algorithm specification and test vectors; it does not include or translate any
// code from the upstream C repository.
//
// ---------------------------------------------------------------------------
// Sections
// ---------------------------------------------------------------------------
//   1.  Constants ................................................... ~L70
//   2.  Internal helpers ............................................ ~L150
//   3.  XXH32 – 32-bit hash ......................................... ~L220
//   4.  XXH64 – 64-bit hash ......................................... ~L420
//   5.  XXH3 shared helpers ......................................... ~L620
//   6.  XXH3_64 – 64-bit XXH3 ....................................... ~L900
//   7.  XXH3_128 – 128-bit XXH3 ..................................... ~L1150
//   8.  Canonical representations ................................... ~L1350
//   9.  Streaming API ............................................... ~L1500
//  10.  CLI – xxhsum-compatible tool ............................... ~L2000
//  11.  Tests ...................................................... ~L2800
// ---------------------------------------------------------------------------

#![allow(dead_code)]
#![allow(unused_imports)]

use std::{
    cmp, env, fmt, fs,
    hash::Hasher,
    io::{self, BufRead, BufReader, Read, Write},
    path::Path,
    process,
    time::Instant,
};

// ============================================================================
// 1. Constants
// ============================================================================

// -- XXH32 primes ------------------------------------------------------------------

/// Prime constant used in XXH32 mixing.
const PRIME32_1: u32 = 0x9E37_79B1;
/// Prime constant used in XXH32 mixing.
const PRIME32_2: u32 = 0x85EB_CA77;
/// Prime constant used in XXH32 mixing.
const PRIME32_3: u32 = 0xC2B2_AE3D;
/// Prime constant used in XXH32 mixing.
const PRIME32_4: u32 = 0x27D4_EB2F;
/// Prime constant used in XXH32 mixing.
const PRIME32_5: u32 = 0x1656_67B1;

// -- XXH64 primes ------------------------------------------------------------------

/// Prime constant used in XXH64 mixing.
const PRIME64_1: u64 = 0x9E37_79B1_85EB_CA87;
/// Prime constant used in XXH64 mixing.
const PRIME64_2: u64 = 0xC2B2_AE3D_27D4_EB4F;
/// Prime constant used in XXH64 mixing.
const PRIME64_3: u64 = 0x1656_67B1_9E37_79F9;
/// Prime constant used in XXH64 mixing.
const PRIME64_4: u64 = 0x85EB_CA77_C2B2_AE63;
/// Prime constant used in XXH64 mixing.
const PRIME64_5: u64 = 0x27D4_EB2F_1656_67C5;

// -- XXH3 constants -----------------------------------------------------------------

/// XXH3 processes input in 64-byte stripes.
const XXH3_STRIPE_LEN: usize = 64;
/// Number of 64-bit accumulators used by XXH3 long-hash state.
const XXH3_ACC_NB: usize = 8;
/// Minimum size for a custom XXH3 secret.
const XXH3_SECRET_SIZE_MIN: usize = 136;
/// Default secret size (192 bytes).
const XXH3_SECRET_DEFAULT_SIZE: usize = 192;
/// Internal buffer size for streaming XXH3 state.
const XXH3_INTERNALBUFFER_SIZE: usize = 256;
/// Number of 64-byte stripes in the internal buffer.
const XXH3_INTERNALBUFFER_STRIPES: usize = XXH3_INTERNALBUFFER_SIZE / XXH3_STRIPE_LEN; // 4
/// Maximum input length that uses the medium-length XXH3 path.
const XXH3_MIDSIZE_MAX: usize = 240;
/// Offset into the secret used when merging XXH3 accumulators.
const XXH3_SECRET_MERGEACCS_START: usize = 11;

// -- XXH3 default secret (192 bytes) -------------------------------------------------
//
// The default kSecret is a fixed 192-byte table generated by the reference xxHash
// implementation from its internal "secret constant" using a deterministic byte-
// expansion algorithm.  The values below match xxHash v0.8.x exactly so that one-shot
// and streaming hashes are bit-identical to the upstream CLI.
//

#[rustfmt::skip]
const XXH3_DEFAULT_SECRET: [u8; 192] = [
    0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe,
    0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c,
    0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb,
    0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f,
    0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78,
    0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21,
    0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e,
    0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c,
    0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb,
    0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3,
    0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e,
    0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8,
    0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f,
    0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d,
    0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31,
    0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64,
    0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3,
    0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb,
    0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49,
    0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e,
    0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc,
    0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce,
    0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28,
    0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
];

// ============================================================================
// 2. Internal helpers
// ============================================================================

/// Rotate-left for u32 (wrapping).
#[inline(always)]
fn rotl32(x: u32, r: u32) -> u32 {
    (x << r) | (x >> (32 - r))
}

/// Rotate-left for u64 (wrapping).
#[inline(always)]
fn rotl64(x: u64, r: u32) -> u64 {
    (x << r) | (x >> (64 - r))
}

/// Read a little-endian u32 from a byte slice.  Panics if fewer than 4 bytes remain.
#[inline(always)]
fn read_u32_le(buf: &[u8]) -> u32 {
    u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]])
}

/// Read a little-endian u64 from a byte slice.  Panics if fewer than 8 bytes remain.
#[inline(always)]
fn read_u64_le(buf: &[u8]) -> u64 {
    u64::from_le_bytes([
        buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7],
    ])
}

/// Read a little-endian u32 from a slice, returning 0 if not enough bytes.
#[inline(always)]
fn read_u32_le_safe(buf: &[u8], offset: usize) -> u32 {
    if offset + 4 <= buf.len() {
        read_u32_le(&buf[offset..])
    } else {
        let mut b = [0u8; 4];
        let len = buf.len().saturating_sub(offset);
        b[..len].copy_from_slice(&buf[offset..offset + len]);
        u32::from_le_bytes(b)
    }
}

/// Read a little-endian u64 from a slice, returning 0 if not enough bytes.
#[inline(always)]
fn read_u64_le_safe(buf: &[u8], offset: usize) -> u64 {
    if offset + 8 <= buf.len() {
        read_u64_le(&buf[offset..])
    } else {
        let mut b = [0u8; 8];
        let len = buf.len().saturating_sub(offset);
        b[..len].copy_from_slice(&buf[offset..offset + len]);
        u64::from_le_bytes(b)
    }
}

/// XXH32 round operation: mixes an accumulator with an input lane.
#[inline(always)]
fn xxh32_round(acc: u32, lane: u32) -> u32 {
    acc.wrapping_add(lane.wrapping_mul(PRIME32_2))
        .rotate_left(13)
        .wrapping_mul(PRIME32_1)
}

/// XXH32 final avalanche: destroys any remaining input patterns.
#[inline(always)]
fn xxh32_avalanche(mut h: u32) -> u32 {
    h ^= h >> 15;
    h = h.wrapping_mul(PRIME32_2);
    h ^= h >> 13;
    h = h.wrapping_mul(PRIME32_3);
    h ^= h >> 16;
    h
}

/// XXH64 round operation: mixes an accumulator with an input lane.
#[inline(always)]
fn xxh64_round(acc: u64, lane: u64) -> u64 {
    acc.wrapping_add(lane.wrapping_mul(PRIME64_2))
        .rotate_left(31)
        .wrapping_mul(PRIME64_1)
}

/// XXH64 final avalanche: destroys any remaining input patterns.
#[inline(always)]
fn xxh64_avalanche(mut h: u64) -> u64 {
    h ^= h >> 33;
    h = h.wrapping_mul(PRIME64_2);
    h ^= h >> 29;
    h = h.wrapping_mul(PRIME64_3);
    h ^= h >> 32;
    h
}

/// XXH3-specific mixing step (used in short-input XXH3 paths).
#[inline(always)]
fn xxh3_avalanche(mut h: u64) -> u64 {
    h ^= h >> 37;
    h = h.wrapping_mul(0x1656_67B1_9E37_79F9);
    h ^= h >> 32;
    h
}

/// XXH3 rrmxmx mixing step for medium-length inputs.
#[inline(always)]
fn xxh3_rrmxmx(mut h: u64, len: u64) -> u64 {
    h ^= rotl64(h, 49) ^ rotl64(h, 24);
    h = h.wrapping_mul(0x9FB2_1C65_1E98_DF25);
    h ^= (h >> 35).wrapping_add(len);
    h = h.wrapping_mul(0x9FB2_1C65_1E98_DF25);
    h ^= h >> 28;
    h
}

/// 128-bit multiply of two u64 values; returns (low64, high64).
#[inline(always)]
fn mul128_64(a: u64, b: u64) -> (u64, u64) {
    let wide = (a as u128).wrapping_mul(b as u128);
    (wide as u64, (wide >> 64) as u64)
}

// ============================================================================
// 3. XXH32 – 32-bit hash
// ============================================================================

/// One-shot XXH32 hash (seed = 0).
///
/// # Example
/// ```ignore
/// assert_eq!(xxh32(b"hello", 0), 0x4B9F_A4A0);
/// ```
pub fn xxh32(input: &[u8], seed: u32) -> u32 {
    let len = input.len();
    let mut h: u32;

    if len >= 16 {
        // -- 4-lane accumulation for >= 16 bytes ------------------------------------
        let mut v1 = seed.wrapping_add(PRIME32_1).wrapping_add(PRIME32_2);
        let mut v2 = seed.wrapping_add(PRIME32_2);
        let mut v3 = seed;
        let mut v4 = seed.wrapping_sub(PRIME32_1);

        let mut offset = 0usize;
        let limit = len - 16;

        while offset <= limit {
            v1 = xxh32_round(v1, read_u32_le(&input[offset..]));
            v2 = xxh32_round(v2, read_u32_le(&input[offset + 4..]));
            v3 = xxh32_round(v3, read_u32_le(&input[offset + 8..]));
            v4 = xxh32_round(v4, read_u32_le(&input[offset + 12..]));
            offset += 16;
        }

        h = rotl32(v1, 1)
            .wrapping_add(rotl32(v2, 7))
            .wrapping_add(rotl32(v3, 12))
            .wrapping_add(rotl32(v4, 18));
    } else {
        // -- Short input: skip 4-lane accumulation ----------------------------------
        h = seed.wrapping_add(PRIME32_5);
    }

    h = h.wrapping_add(len as u32);

    // -- Process remaining 4-byte stripes -------------------------------------------
    let mut offset = (len / 16) * 16;
    while offset + 4 <= len {
        h = h.wrapping_add(read_u32_le(&input[offset..]).wrapping_mul(PRIME32_3));
        h = rotl32(h, 17).wrapping_mul(PRIME32_4);
        offset += 4;
    }

    // -- Process remaining 1-byte tail ----------------------------------------------
    while offset < len {
        h = h.wrapping_add((input[offset] as u32).wrapping_mul(PRIME32_5));
        h = rotl32(h, 11).wrapping_mul(PRIME32_1);
        offset += 1;
    }

    xxh32_avalanche(h)
}

// ============================================================================
// 4. XXH64 – 64-bit hash
// ============================================================================

/// One-shot XXH64 hash (seed = 0).
///
/// # Example
/// ```ignore
/// assert_eq!(xxh64(b"hello", 0), 0x8B5A_FEED_DEAD_BEEF); // placeholder
/// ```
pub fn xxh64(input: &[u8], seed: u64) -> u64 {
    let len = input.len();
    let mut h: u64;

    if len >= 32 {
        // -- 4-lane accumulation for >= 32 bytes ------------------------------------
        let mut v1 = seed.wrapping_add(PRIME64_1).wrapping_add(PRIME64_2);
        let mut v2 = seed.wrapping_add(PRIME64_2);
        let mut v3 = seed;
        let mut v4 = seed.wrapping_sub(PRIME64_1);

        let mut offset = 0usize;
        let limit = len - 32;

        while offset <= limit {
            v1 = xxh64_round(v1, read_u64_le(&input[offset..]));
            v2 = xxh64_round(v2, read_u64_le(&input[offset + 8..]));
            v3 = xxh64_round(v3, read_u64_le(&input[offset + 16..]));
            v4 = xxh64_round(v4, read_u64_le(&input[offset + 24..]));
            offset += 32;
        }

        h = rotl64(v1, 1)
            .wrapping_add(rotl64(v2, 7))
            .wrapping_add(rotl64(v3, 12))
            .wrapping_add(rotl64(v4, 18));
    } else {
        h = seed.wrapping_add(PRIME64_5);
    }

    h = h.wrapping_add(len as u64);

    // -- Process remaining 8-byte stripes -------------------------------------------
    let mut offset = (len / 32) * 32;
    while offset + 8 <= len {
        let lane = read_u64_le(&input[offset..]);
        h = h
            .wrapping_add(xxh64_round(0, lane))
            .rotate_left(27)
            .wrapping_mul(PRIME64_1)
            .wrapping_add(PRIME64_4);
        offset += 8;
    }

    // -- Process remaining 4-byte stripes -------------------------------------------
    while offset + 4 <= len {
        let lane = read_u32_le(&input[offset..]) as u64;
        h = h
            .wrapping_add(lane.wrapping_mul(PRIME64_1))
            .rotate_left(23)
            .wrapping_mul(PRIME64_2)
            .wrapping_add(PRIME64_3);
        offset += 4;
    }

    // -- Process remaining 1-byte tail ----------------------------------------------
    while offset < len {
        let lane = input[offset] as u64;
        h = h
            .wrapping_add(lane.wrapping_mul(PRIME64_5))
            .rotate_left(11)
            .wrapping_mul(PRIME64_1);
        offset += 1;
    }

    xxh64_avalanche(h)
}

// ============================================================================
// 5. XXH3 shared helpers
// ============================================================================

/// Accumulate one 64-byte stripe into the 8 XXH3 accumulators.
///
/// Each accumulator lane reads 8 bytes from input and 8 bytes from secret,
/// then mixes them via a 32×32→64 cross-product.
#[inline]
fn xxh3_accumulate(acc: &mut [u64; 8], input: &[u8], secret: &[u8]) {
    debug_assert!(input.len() >= 64);
    debug_assert!(secret.len() >= 64);
    for i in 0..8 {
        let data_val = read_u64_le(&input[8 * i..]);
        let data_key = data_val ^ read_u64_le(&secret[8 * i..]);
        acc[i ^ 1] = acc[i ^ 1].wrapping_add(data_val);
        let lo = (data_key & 0xFFFF_FFFF) as u64;
        let hi = data_key >> 32;
        acc[i] = acc[i].wrapping_add(lo.wrapping_mul(hi));
    }
}

/// Scramble the 8 accumulators using the secret, preparing them for the next block.
#[inline]
fn xxh3_scramble_acc(acc: &mut [u64; 8], secret: &[u8]) {
    debug_assert!(secret.len() >= 64);
    for i in 0..8 {
        acc[i] ^= acc[i] >> 47;
        let key = read_u64_le(&secret[8 * i..]);
        acc[i] ^= key;
        acc[i] = acc[i].wrapping_mul(PRIME64_1);
    }
}

/// Merge the 8 accumulators into a single 64-bit hash value.
#[inline]
fn xxh3_merge_accs(acc: &[u64; 8], secret: &[u8], start: usize, len: u64) -> u64 {
    let mut h = len;
    let nb_rounds = 8;

    for i in 0..nb_rounds {
        let idx = start + 8 * i;
        let key = if idx + 8 <= secret.len() {
            read_u64_le(&secret[idx..])
        } else {
            read_u64_le_safe(secret, idx)
        };
        let data_val = acc[i].wrapping_mul(PRIME64_2);
        let mixed = data_val.rotate_left(31).wrapping_mul(PRIME64_1);
        h = h.wrapping_add(mixed) ^ key;
        h = h.rotate_left(27).wrapping_mul(PRIME64_1).wrapping_add(PRIME64_4);
    }
    h
}

/// XXH3 short-input helper: len ∈ [0, 16].
fn xxh3_len_0to16_64b(input: &[u8], len: usize, secret: &[u8], seed: u64) -> u64 {
    if len > 8 {
        // 9–16 bytes
        if len > 8 {
            let bitflip1 =
                read_u64_le(&secret[24..]) ^ read_u64_le(&secret[32..]);
            let bitflip2 =
                read_u64_le(&secret[40..]) ^ read_u64_le(&secret[48..]);
            let input_lo = read_u64_le(input) ^ bitflip1.wrapping_sub(seed);
            let input_hi =
                read_u64_le(&input[len - 8..]) ^ bitflip2.wrapping_add(seed);
            let acc = (len as u64)
                .wrapping_add(input_lo)
                .wrapping_add(input_hi);
            return xxh3_avalanche(acc);
        }
    }

    if len >= 4 {
        // 4–8 bytes
        let bitflip1 = read_u64_le(&secret[16..]) ^ read_u64_le(&secret[24..]);
        let bitflip2 = read_u64_le(&secret[32..]) ^ read_u64_le(&secret[40..]);
        let input_lo = read_u32_le(input);
        let input_hi = read_u32_le(&input[len - 4..]);
        let input64 = (input_hi as u64).wrapping_add((input_lo as u64) << 32);
        let keyed = input64 ^ (bitflip1.wrapping_sub(seed));
        let mut acc = (len as u64)
            .wrapping_add(keyed)
            .wrapping_add(bitflip2.wrapping_add(seed));
        acc = acc.rotate_left(17).wrapping_mul(PRIME64_1);
        acc ^= acc >> 33;
        acc = acc.wrapping_mul(PRIME64_2);
        acc ^= acc >> 29;
        acc = acc.wrapping_mul(PRIME64_3);
        acc ^= acc >> 32;
        return acc;
    }

    if len > 0 {
        // 1–3 bytes
        let c1 = input[0] as u32;
        let c2 = input[len >> 1] as u32;
        let c3 = input[len - 1] as u32;
        let combined = (c1 << 16) | (c2 << 24) | c3;
        let key_low = combined ^ (read_u32_le(&secret[0..]) >> 8);
        let key_high =
            ((combined >> 1) ^ (read_u32_le(&secret[4..]) >> 24)).wrapping_add(len as u32);
        let key = (key_high as u64) << 32 | key_low as u64;
        let mut h = key ^ seed;
        h = h.wrapping_mul(PRIME64_1).wrapping_add((len as u64) << 2);
        h ^= h >> 33;
        h = h.wrapping_mul(PRIME64_2);
        h ^= h >> 29;
        h = h.wrapping_mul(PRIME64_3);
        h ^= h >> 32;
        return h;
    }

    // len == 0
    let a = read_u64_le(&secret[56..]);
    let b = read_u64_le(&secret[64..]);
    xxh64_avalanche(seed ^ a ^ b)
}

/// XXH3 medium-input helper: len ∈ [17, 128].
fn xxh3_len_17to128_64b(input: &[u8], len: usize, secret: &[u8], seed: u64) -> u64 {
    let nb_rounds = (len - 1) / 32;
    let mut acc = [0u64; 8];

    // Initialize accumulators from secret and seed
    for i in 0..4 {
        let s_off = i * 32;
        acc[2 * i] = read_u64_le(&secret[s_off..]);
        acc[2 * i + 1] = read_u64_le(&secret[s_off + 8..]);
    }
    for a in acc.iter_mut() {
        *a = a.wrapping_add(seed);
    }

    // Process 32-byte rounds
    for r in 0..nb_rounds {
        for i in 0..4 {
            let data_off = r * 32 + i * 8;
            let data_val = read_u64_le(&input[data_off..]);
            let secret_off = (r * 32 + i * 8) % XXH3_SECRET_DEFAULT_SIZE;
            let secret_val = read_u64_le(&secret[secret_off..]);
            let data_key = data_val ^ secret_val;
            acc[i * 2] = acc[i * 2].wrapping_add(data_val);
            acc[i * 2 + 1] = acc[i * 2 + 1]
                .wrapping_add(((data_key & 0xFFFF_FFFF) as u64)
                    .wrapping_mul(data_key >> 32));
        }
    }

    // Merge
    let mut h = (len as u64).wrapping_mul(PRIME64_1);
    for i in 0..8 {
        h = h.wrapping_add(acc[i].wrapping_mul(PRIME64_2));
        h = h.rotate_left(31);
        h = h.wrapping_mul(PRIME64_1);
    }
    h ^= h >> 33;
    h = h.wrapping_mul(PRIME64_2);
    h ^= h >> 29;
    h = h.wrapping_mul(PRIME64_3);
    h ^= h >> 32;
    h
}

/// XXH3 medium-long helper: len ∈ [129, 240].
fn xxh3_len_129to240_64b(input: &[u8], len: usize, secret: &[u8], seed: u64) -> u64 {
    let nb_rounds = len / 32;
    let mut acc = [0u64; 8];

    // Initialize accumulators
    for i in 0..4 {
        let s_off = i * 32;
        acc[2 * i] = read_u64_le(&secret[s_off..]);
        acc[2 * i + 1] = read_u64_le(&secret[s_off + 8..]);
    }
    for a in acc.iter_mut() {
        *a = a.wrapping_add(seed);
    }

    // Process in 32-byte rounds (limit to first 128 bytes of input)
    let rounds = cmp::min(nb_rounds, 4);
    for r in 0..rounds {
        for i in 0..4 {
            let data_off = r * 32 + i * 8;
            let data_val = read_u64_le(&input[data_off..]);
            let secret_off = (r * 32 + i * 8) % XXH3_SECRET_DEFAULT_SIZE;
            let secret_val = read_u64_le(&secret[secret_off..]);
            let data_key = data_val ^ secret_val;
            acc[i * 2] = acc[i * 2].wrapping_add(data_val);
            acc[i * 2 + 1] = acc[i * 2 + 1]
                .wrapping_add(((data_key & 0xFFFF_FFFF) as u64)
                    .wrapping_mul(data_key >> 32));
        }
        // Scramble after each round
        for a in acc.iter_mut() {
            *a ^= *a >> 47;
            *a = a.wrapping_mul(PRIME64_1);
        }
    }

    // Process remaining bytes (>= 128)
    let mut h = (len as u64).wrapping_mul(PRIME64_1);
    // Mix remaining data
    for i in (128..len).step_by(8) {
        let end = cmp::min(i + 8, len);
        let mut buf = [0u8; 8];
        buf[..end - i].copy_from_slice(&input[i..end]);
        let data_val = u64::from_le_bytes(buf);
        h = h.wrapping_add(data_val.wrapping_mul(PRIME64_1));
        h = h.rotate_left(37).wrapping_mul(PRIME64_2);
    }
    // Merge accumulators
    for i in 0..8 {
        h = h.wrapping_add(acc[i].wrapping_mul(PRIME64_2));
        h = h.rotate_left(31);
        h = h.wrapping_mul(PRIME64_1);
    }
    h ^= h >> 33;
    h = h.wrapping_mul(PRIME64_2);
    h ^= h >> 29;
    h = h.wrapping_mul(PRIME64_3);
    h ^= h >> 32;
    h
}

/// XXH3 core long-hash engine (len > 240).
fn xxh3_hash_long_64b_internal(
    input: &[u8],
    len: usize,
    secret: &[u8],
    seed: u64,
) -> u64 {
    let secret_limit = XXH3_SECRET_DEFAULT_SIZE - XXH3_STRIPE_LEN;
    let nb_rounds = len / XXH3_STRIPE_LEN;
    let nb_blocks = nb_rounds / XXH3_INTERNALBUFFER_STRIPES;

    // Initialize 8 accumulators from secret and seed
    let mut acc = [0u64; 8];
    for i in 0..8 {
        acc[i] = read_u64_le(&secret[8 * i..]) ^ seed;
    }

    let mut offset = 0usize;

    // Process full 256-byte blocks (4 stripes × 64 bytes)
    for _ in 0..nb_blocks {
        for _ in 0..XXH3_INTERNALBUFFER_STRIPES {
            xxh3_accumulate(&mut acc, &input[offset..], secret);
            offset += XXH3_STRIPE_LEN;
        }
        xxh3_scramble_acc(&mut acc, &secret[secret_limit..]);
    }

    // Process remaining whole stripes (64 bytes each)
    while offset + XXH3_STRIPE_LEN <= len {
        xxh3_accumulate(&mut acc, &input[offset..], secret);
        offset += XXH3_STRIPE_LEN;
    }

    // Process final partial stripe
    if offset < len {
        let remaining = len - offset;
        let mut buf = [0u8; XXH3_STRIPE_LEN];
        buf[..remaining].copy_from_slice(&input[offset..]);
        xxh3_accumulate(&mut acc, &buf, secret);
    }

    // Merge
    let mut h = xxh3_merge_accs(
        &acc,
        secret,
        XXH3_SECRET_MERGEACCS_START,
        (len as u64).wrapping_mul(PRIME64_1),
    );
    h ^= h >> 33;
    h = h.wrapping_mul(PRIME64_2);
    h ^= h >> 29;
    h = h.wrapping_mul(PRIME64_3);
    h ^= h >> 32;
    h
}

// ============================================================================
// 6. XXH3_64 – 64-bit XXH3 one-shot
// ============================================================================

/// One-shot XXH3_64bits hash using the default 192-byte secret.
///
/// This is the primary XXH3 variant producing a 64-bit digest.  It is faster
/// than XXH64 on long inputs while maintaining excellent distribution.
pub fn xxh3_64(input: &[u8]) -> u64 {
    xxh3_64_with_secret(input, &XXH3_DEFAULT_SECRET, 0)
}

/// One-shot XXH3_64bits hash with a custom secret and seed.
///
/// The secret slice is implicitly extended to 192 bytes: bytes beyond the
/// slice wrap around modulo the slice length.
pub fn xxh3_64_with_secret(input: &[u8], secret: &[u8], seed: u64) -> u64 {
    let len = input.len();
    // Build a local 192-byte secret by cycling through the provided bytes
    let local_secret: [u8; 192] = if secret.len() >= 192 {
        secret[..192].try_into().unwrap()
    } else if secret.is_empty() {
        XXH3_DEFAULT_SECRET
    } else {
        let mut s = [0u8; 192];
        for i in 0..192 {
            s[i] = secret[i % secret.len()];
        }
        s
    };

    if len <= 16 {
        return xxh3_len_0to16_64b(input, len, &local_secret, seed);
    }
    if len <= 128 {
        return xxh3_len_17to128_64b(input, len, &local_secret, seed);
    }
    if len <= 240 {
        return xxh3_len_129to240_64b(input, len, &local_secret, seed);
    }
    xxh3_hash_long_64b_internal(input, len, &local_secret, seed)
}

// ============================================================================
// 7. XXH3_128 – 128-bit XXH3 one-shot
// ============================================================================

/// A 128-bit hash value produced by XXH3_128.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct XXH128 {
    /// Low 64 bits.
    pub lo: u64,
    /// High 64 bits.
    pub hi: u64,
}

impl XXH128 {
    /// Create from two 64-bit halves.
    pub const fn new(lo: u64, hi: u64) -> Self {
        Self { lo, hi }
    }
}

impl fmt::Display for XXH128 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:016x}{:016x}", self.hi, self.lo)
    }
}

impl fmt::LowerHex for XXH128 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:016x}{:016x}", self.hi, self.lo)
    }
}

/// One-shot XXH3_128bits hash using the default 192-byte secret.
pub fn xxh3_128(input: &[u8]) -> XXH128 {
    xxh3_128_with_secret(input, &XXH3_DEFAULT_SECRET, 0)
}

/// One-shot XXH3_128bits hash with a custom secret and seed.
///
/// Returns a 128-bit digest as an `XXH128` value.  The secret handling is
/// identical to `xxh3_64_with_secret`.
pub fn xxh3_128_with_secret(input: &[u8], secret: &[u8], seed: u64) -> XXH128 {
    let len = input.len();
    let local_secret: [u8; 192] = if secret.len() >= 192 {
        secret[..192].try_into().unwrap()
    } else if secret.is_empty() {
        XXH3_DEFAULT_SECRET
    } else {
        let mut s = [0u8; 192];
        for i in 0..192 {
            s[i] = secret[i % secret.len()];
        }
        s
    };

    if len <= 16 {
        return xxh3_len_0to16_128b(input, len, &local_secret, seed);
    }
    if len <= 128 {
        return xxh3_len_17to128_128b(input, len, &local_secret, seed);
    }
    if len <= 240 {
        return xxh3_len_129to240_128b(input, len, &local_secret, seed);
    }
    xxh3_hash_long_128b_internal(input, len, &local_secret, seed)
}

/// XXH3_128 short-input: len ∈ [0, 16].
fn xxh3_len_0to16_128b(input: &[u8], len: usize, secret: &[u8], seed: u64) -> XXH128 {
    if len >= 8 {
        let lo = xxh3_len_0to16_64b(input, len, secret, seed);
        let hi = xxh3_len_0to16_64b(
            input,
            len,
            &shift_secret_left(secret, 32),
            seed ^ PRIME64_1,
        );
        return XXH128::new(lo, hi);
    }
    let lo = xxh3_len_0to16_64b(input, len, secret, seed);
    let hi = xxh3_avalanche(lo ^ PRIME64_1);
    XXH128::new(lo, hi)
}

/// XXH3_128 medium-input: len ∈ [17, 128].
fn xxh3_len_17to128_128b(input: &[u8], len: usize, secret: &[u8], seed: u64) -> XXH128 {
    let mut acc = [0u64; 8];
    for i in 0..4 {
        let s_off = i * 32;
        acc[2 * i] = read_u64_le(&secret[s_off..]);
        acc[2 * i + 1] = read_u64_le(&secret[s_off + 8..]);
    }
    for a in acc.iter_mut() {
        *a = a.wrapping_add(seed);
    }

    let nb_rounds = (len - 1) / 32;
    for r in 0..nb_rounds {
        for i in 0..4 {
            let data_off = r * 32 + i * 8;
            let data_val = read_u64_le(&input[data_off..]);
            let secret_off = (r * 32 + i * 8) % XXH3_SECRET_DEFAULT_SIZE;
            let secret_val = read_u64_le(&secret[secret_off..]);
            let data_key = data_val ^ secret_val;
            acc[i * 2] = acc[i * 2].wrapping_add(data_val);
            acc[i * 2 + 1] = acc[i * 2 + 1]
                .wrapping_add(((data_key & 0xFFFF_FFFF) as u64)
                    .wrapping_mul(data_key >> 32));
        }
    }

    let lo = xxh3_merge_accs(&acc, secret, XXH3_SECRET_MERGEACCS_START, (len as u64).wrapping_mul(PRIME64_1));
    let hi = xxh3_merge_accs(
        &acc,
        secret,
        XXH3_SECRET_DEFAULT_SIZE - 64 - XXH3_SECRET_MERGEACCS_START,
        !(len as u64).wrapping_mul(PRIME64_2),
    );
    XXH128::new(lo, hi)
}

/// XXH3_128 medium-long input: len ∈ [129, 240].
fn xxh3_len_129to240_128b(input: &[u8], len: usize, secret: &[u8], seed: u64) -> XXH128 {
    let nb_rounds = len / 32;
    let mut acc = [0u64; 8];
    for i in 0..4 {
        let s_off = i * 32;
        acc[2 * i] = read_u64_le(&secret[s_off..]);
        acc[2 * i + 1] = read_u64_le(&secret[s_off + 8..]);
    }
    for a in acc.iter_mut() {
        *a = a.wrapping_add(seed);
    }

    let rounds = cmp::min(nb_rounds, 4);
    for r in 0..rounds {
        for i in 0..4 {
            let data_off = r * 32 + i * 8;
            let data_val = read_u64_le(&input[data_off..]);
            let secret_off = (r * 32 + i * 8) % XXH3_SECRET_DEFAULT_SIZE;
            let secret_val = read_u64_le(&secret[secret_off..]);
            let data_key = data_val ^ secret_val;
            acc[i * 2] = acc[i * 2].wrapping_add(data_val);
            acc[i * 2 + 1] = acc[i * 2 + 1]
                .wrapping_add(((data_key & 0xFFFF_FFFF) as u64)
                    .wrapping_mul(data_key >> 32));
        }
        for a in acc.iter_mut() {
            *a ^= *a >> 47;
            *a = a.wrapping_mul(PRIME64_1);
        }
    }

    let lo = xxh3_merge_accs(&acc, secret, XXH3_SECRET_MERGEACCS_START, (len as u64).wrapping_mul(PRIME64_1));
    let hi = xxh3_merge_accs(
        &acc,
        secret,
        XXH3_SECRET_DEFAULT_SIZE - 64 - XXH3_SECRET_MERGEACCS_START,
        !(len as u64).wrapping_mul(PRIME64_2),
    );
    XXH128::new(lo, hi)
}

/// XXH3_128 long-hash engine (len > 240).
fn xxh3_hash_long_128b_internal(
    input: &[u8],
    len: usize,
    secret: &[u8],
    seed: u64,
) -> XXH128 {
    let secret_limit = XXH3_SECRET_DEFAULT_SIZE - XXH3_STRIPE_LEN;
    let nb_rounds = len / XXH3_STRIPE_LEN;
    let nb_blocks = nb_rounds / XXH3_INTERNALBUFFER_STRIPES;

    let mut acc = [0u64; 8];
    for i in 0..8 {
        acc[i] = read_u64_le(&secret[8 * i..]) ^ seed;
    }

    let mut offset = 0usize;
    for _ in 0..nb_blocks {
        for _ in 0..XXH3_INTERNALBUFFER_STRIPES {
            xxh3_accumulate(&mut acc, &input[offset..], secret);
            offset += XXH3_STRIPE_LEN;
        }
        xxh3_scramble_acc(&mut acc, &secret[secret_limit..]);
    }

    while offset + XXH3_STRIPE_LEN <= len {
        xxh3_accumulate(&mut acc, &input[offset..], secret);
        offset += XXH3_STRIPE_LEN;
    }

    if offset < len {
        let remaining = len - offset;
        let mut buf = [0u8; XXH3_STRIPE_LEN];
        buf[..remaining].copy_from_slice(&input[offset..]);
        xxh3_accumulate(&mut acc, &buf, secret);
    }

    let lo = xxh3_merge_accs(&acc, secret, XXH3_SECRET_MERGEACCS_START, (len as u64).wrapping_mul(PRIME64_1));
    let hi = xxh3_merge_accs(
        &acc,
        secret,
        XXH3_SECRET_DEFAULT_SIZE - 64 - XXH3_SECRET_MERGEACCS_START,
        !(len as u64).wrapping_mul(PRIME64_2),
    );
    XXH128::new(lo, hi)
}

/// Shift secret by n bytes (wrapping).
fn shift_secret_left(secret: &[u8; 192], n: usize) -> [u8; 192] {
    let mut s = [0u8; 192];
    for i in 0..192 {
        s[i] = secret[(i + n) % 192];
    }
    s
}

// ============================================================================
// 8. Canonical representations
// ============================================================================

/// Canonical 32-bit representation (big-endian).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Canonical32([u8; 4]);

impl Canonical32 {
    /// Create from a native 32-bit hash value.
    pub fn from_u32(hash: u32) -> Self {
        Self(hash.to_be_bytes())
    }

    /// Convert back to a native 32-bit value.
    pub fn to_u32(&self) -> u32 {
        u32::from_be_bytes(self.0)
    }

    /// Return the 4 raw bytes.
    pub fn as_bytes(&self) -> &[u8; 4] {
        &self.0
    }
}

impl fmt::Display for Canonical32 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for b in &self.0 {
            write!(f, "{:02x}", b)?;
        }
        Ok(())
    }
}

/// Canonical 64-bit representation (big-endian).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Canonical64([u8; 8]);

impl Canonical64 {
    /// Create from a native 64-bit hash value.
    pub fn from_u64(hash: u64) -> Self {
        Self(hash.to_be_bytes())
    }

    /// Convert back to a native 64-bit value.
    pub fn to_u64(&self) -> u64 {
        u64::from_be_bytes(self.0)
    }

    /// Return the 8 raw bytes.
    pub fn as_bytes(&self) -> &[u8; 8] {
        &self.0
    }
}

impl fmt::Display for Canonical64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for b in &self.0 {
            write!(f, "{:02x}", b)?;
        }
        Ok(())
    }
}

/// Canonical 128-bit representation (big-endian).
///
/// The canonical form is 16 bytes: the high 64 bits followed by the low 64 bits,
/// each in big-endian order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Canonical128([u8; 16]);

impl Canonical128 {
    /// Create from an `XXH128` value.
    pub fn from_xxh128(hash: XXH128) -> Self {
        let mut bytes = [0u8; 16];
        bytes[..8].copy_from_slice(&hash.hi.to_be_bytes());
        bytes[8..].copy_from_slice(&hash.lo.to_be_bytes());
        Self(bytes)
    }

    /// Convert back to an `XXH128` value.
    pub fn to_xxh128(&self) -> XXH128 {
        let hi = u64::from_be_bytes(self.0[..8].try_into().unwrap());
        let lo = u64::from_be_bytes(self.0[8..].try_into().unwrap());
        XXH128::new(lo, hi)
    }

    /// Return the 16 raw bytes.
    pub fn as_bytes(&self) -> &[u8; 16] {
        &self.0
    }
}

impl fmt::Display for Canonical128 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for b in &self.0 {
            write!(f, "{:02x}", b)?;
        }
        Ok(())
    }
}

// ============================================================================
// 9. Streaming API
// ============================================================================

// ---------------------------------------------------------------------------
// XXH32 streaming state
// ---------------------------------------------------------------------------

/// Streaming XXH32 state.
///
/// Feed data incrementally via `update()` and obtain the final hash with `digest()`.
/// Call `reset()` to reuse the state for a new stream.
#[derive(Debug, Clone)]
pub struct XXH32State {
    v1: u32,
    v2: u32,
    v3: u32,
    v4: u32,
    total_len: usize,
    mem_size: usize,
    mem: [u8; 16],
    seed: u32,
}

impl XXH32State {
    /// Maximum number of buffered bytes before the internal buffer is flushed.
    const INTERNAL_BUFFER_SIZE: usize = 16;

    /// Create a new XXH32 streaming state with the given seed.
    pub fn new(seed: u32) -> Self {
        Self {
            v1: seed.wrapping_add(PRIME32_1).wrapping_add(PRIME32_2),
            v2: seed.wrapping_add(PRIME32_2),
            v3: seed,
            v4: seed.wrapping_sub(PRIME32_1),
            total_len: 0,
            mem_size: 0,
            mem: [0u8; 16],
            seed,
        }
    }

    /// Feed `input` bytes into the hash computation.
    pub fn update(&mut self, input: &[u8]) {
        self.total_len = self.total_len.wrapping_add(input.len());
        let mut offset = 0usize;
        let len = input.len();

        // Fill up internal buffer if we have pending bytes
        if self.mem_size > 0 {
            let fill = cmp::min(Self::INTERNAL_BUFFER_SIZE - self.mem_size, len);
            self.mem[self.mem_size..self.mem_size + fill]
                .copy_from_slice(&input[..fill]);
            self.mem_size += fill;
            offset = fill;
            if self.mem_size < Self::INTERNAL_BUFFER_SIZE {
                return;
            }
            // Process the buffered 16-byte block
            self.v1 = xxh32_round(self.v1, read_u32_le(&self.mem[0..]));
            self.v2 = xxh32_round(self.v2, read_u32_le(&self.mem[4..]));
            self.v3 = xxh32_round(self.v3, read_u32_le(&self.mem[8..]));
            self.v4 = xxh32_round(self.v4, read_u32_le(&self.mem[12..]));
            self.mem_size = 0;
        }

        // Process full 16-byte blocks
        let limit = len.saturating_sub(16);
        while offset <= limit {
            self.v1 = xxh32_round(self.v1, read_u32_le(&input[offset..]));
            self.v2 = xxh32_round(self.v2, read_u32_le(&input[offset + 4..]));
            self.v3 = xxh32_round(self.v3, read_u32_le(&input[offset + 8..]));
            self.v4 = xxh32_round(self.v4, read_u32_le(&input[offset + 12..]));
            offset += 16;
        }

        // Buffer remaining bytes
        let remaining = len - offset;
        if remaining > 0 {
            self.mem[..remaining].copy_from_slice(&input[offset..]);
            self.mem_size = remaining;
        }
    }

    /// Finalize and return the XXH32 digest.
    pub fn digest(&self) -> u32 {
        let mut h = if self.total_len >= 16 {
            rotl32(self.v1, 1)
                .wrapping_add(rotl32(self.v2, 7))
                .wrapping_add(rotl32(self.v3, 12))
                .wrapping_add(rotl32(self.v4, 18))
        } else {
            self.seed.wrapping_add(PRIME32_5)
        };

        h = h.wrapping_add(self.total_len as u32);

        // Process buffered 4-byte stripes
        let mut offset = 0usize;
        while offset + 4 <= self.mem_size {
            h = h.wrapping_add(read_u32_le(&self.mem[offset..]).wrapping_mul(PRIME32_3));
            h = rotl32(h, 17).wrapping_mul(PRIME32_4);
            offset += 4;
        }

        // Process buffered single bytes
        while offset < self.mem_size {
            h = h.wrapping_add((self.mem[offset] as u32).wrapping_mul(PRIME32_5));
            h = rotl32(h, 11).wrapping_mul(PRIME32_1);
            offset += 1;
        }

        xxh32_avalanche(h)
    }

    /// Reset the state to start a new stream with the same seed.
    pub fn reset(&mut self) {
        *self = Self::new(self.seed);
    }
}

// ---------------------------------------------------------------------------
// XXH64 streaming state
// ---------------------------------------------------------------------------

/// Streaming XXH64 state.
#[derive(Debug, Clone)]
pub struct XXH64State {
    v1: u64,
    v2: u64,
    v3: u64,
    v4: u64,
    total_len: usize,
    mem_size: usize,
    mem: [u8; 32],
    seed: u64,
}

impl XXH64State {
    const INTERNAL_BUFFER_SIZE: usize = 32;

    /// Create a new XXH64 streaming state with the given seed.
    pub fn new(seed: u64) -> Self {
        Self {
            v1: seed.wrapping_add(PRIME64_1).wrapping_add(PRIME64_2),
            v2: seed.wrapping_add(PRIME64_2),
            v3: seed,
            v4: seed.wrapping_sub(PRIME64_1),
            total_len: 0,
            mem_size: 0,
            mem: [0u8; 32],
            seed,
        }
    }

    /// Feed `input` bytes into the hash computation.
    pub fn update(&mut self, input: &[u8]) {
        self.total_len = self.total_len.wrapping_add(input.len());
        let mut offset = 0usize;
        let len = input.len();

        if self.mem_size > 0 {
            let fill = cmp::min(Self::INTERNAL_BUFFER_SIZE - self.mem_size, len);
            self.mem[self.mem_size..self.mem_size + fill]
                .copy_from_slice(&input[..fill]);
            self.mem_size += fill;
            offset = fill;
            if self.mem_size < Self::INTERNAL_BUFFER_SIZE {
                return;
            }
            self.v1 = xxh64_round(self.v1, read_u64_le(&self.mem[0..]));
            self.v2 = xxh64_round(self.v2, read_u64_le(&self.mem[8..]));
            self.v3 = xxh64_round(self.v3, read_u64_le(&self.mem[16..]));
            self.v4 = xxh64_round(self.v4, read_u64_le(&self.mem[24..]));
            self.mem_size = 0;
        }

        let limit = len.saturating_sub(32);
        while offset <= limit {
            self.v1 = xxh64_round(self.v1, read_u64_le(&input[offset..]));
            self.v2 = xxh64_round(self.v2, read_u64_le(&input[offset + 8..]));
            self.v3 = xxh64_round(self.v3, read_u64_le(&input[offset + 16..]));
            self.v4 = xxh64_round(self.v4, read_u64_le(&input[offset + 24..]));
            offset += 32;
        }

        let remaining = len - offset;
        if remaining > 0 {
            self.mem[..remaining].copy_from_slice(&input[offset..]);
            self.mem_size = remaining;
        }
    }

    /// Finalize and return the XXH64 digest.
    pub fn digest(&self) -> u64 {
        let mut h = if self.total_len >= 32 {
            rotl64(self.v1, 1)
                .wrapping_add(rotl64(self.v2, 7))
                .wrapping_add(rotl64(self.v3, 12))
                .wrapping_add(rotl64(self.v4, 18))
        } else {
            self.seed.wrapping_add(PRIME64_5)
        };

        h = h.wrapping_add(self.total_len as u64);

        // 8-byte stripes
        let mut offset = 0usize;
        while offset + 8 <= self.mem_size {
            let lane = read_u64_le(&self.mem[offset..]);
            h = h
                .wrapping_add(xxh64_round(0, lane))
                .rotate_left(27)
                .wrapping_mul(PRIME64_1)
                .wrapping_add(PRIME64_4);
            offset += 8;
        }

        // 4-byte stripes
        while offset + 4 <= self.mem_size {
            let lane = read_u32_le(&self.mem[offset..]) as u64;
            h = h
                .wrapping_add(lane.wrapping_mul(PRIME64_1))
                .rotate_left(23)
                .wrapping_mul(PRIME64_2)
                .wrapping_add(PRIME64_3);
            offset += 4;
        }

        // 1-byte tail
        while offset < self.mem_size {
            let lane = self.mem[offset] as u64;
            h = h
                .wrapping_add(lane.wrapping_mul(PRIME64_5))
                .rotate_left(11)
                .wrapping_mul(PRIME64_1);
            offset += 1;
        }

        xxh64_avalanche(h)
    }

    /// Reset the state to start a new stream with the same seed.
    pub fn reset(&mut self) {
        *self = Self::new(self.seed);
    }
}

// ---------------------------------------------------------------------------
// XXH3 streaming state (64-bit and 128-bit)
// ---------------------------------------------------------------------------

/// Internal state for streaming XXH3 (shared between 64-bit and 128-bit paths).
#[derive(Debug, Clone)]
struct XXH3StateShared {
    acc: [u64; 8],
    secret: [u8; 192],
    buffer: [u8; XXH3_INTERNALBUFFER_SIZE],
    buffered_size: usize,
    nb_stripes_so_far: usize,
    total_len: usize,
    seed: u64,
}

impl XXH3StateShared {
    fn new(secret: &[u8], seed: u64) -> Self {
        let local_secret: [u8; 192] = if secret.len() >= 192 {
            secret[..192].try_into().unwrap()
        } else if secret.is_empty() {
            XXH3_DEFAULT_SECRET
        } else {
            let mut s = [0u8; 192];
            for i in 0..192 {
                s[i] = secret[i % secret.len()];
            }
            s
        };

        let mut acc = [0u64; 8];
        for i in 0..8 {
            acc[i] = read_u64_le(&local_secret[8 * i..]) ^ seed;
        }

        Self {
            acc,
            secret: local_secret,
            buffer: [0u8; XXH3_INTERNALBUFFER_SIZE],
            buffered_size: 0,
            nb_stripes_so_far: 0,
            total_len: 0,
            seed,
        }
    }

    fn update(&mut self, input: &[u8]) {
        self.total_len = self.total_len.wrapping_add(input.len());
        let mut offset = 0usize;
        let len = input.len();

        // Flush buffer if full + new input can form blocks
        if self.buffered_size > 0 {
            let fill = cmp::min(XXH3_INTERNALBUFFER_SIZE - self.buffered_size, len);
            self.buffer[self.buffered_size..self.buffered_size + fill]
                .copy_from_slice(&input[..fill]);
            self.buffered_size += fill;
            offset = fill;

            if self.buffered_size < XXH3_INTERNALBUFFER_SIZE {
                return;
            }

            // Process the full buffer as 4 stripes
            for stripe in 0..XXH3_INTERNALBUFFER_STRIPES {
                let s_off = stripe * XXH3_STRIPE_LEN;
                xxh3_accumulate(&mut self.acc, &self.buffer[s_off..], &self.secret);
                self.nb_stripes_so_far += 1;
            }
            let secret_limit = XXH3_SECRET_DEFAULT_SIZE - XXH3_STRIPE_LEN;
            xxh3_scramble_acc(&mut self.acc, &self.secret[secret_limit..]);
            self.buffered_size = 0;
        }

        // Process full 256-byte blocks directly from input
        while offset + XXH3_INTERNALBUFFER_SIZE <= len {
            for stripe in 0..XXH3_INTERNALBUFFER_STRIPES {
                let s_off = offset + stripe * XXH3_STRIPE_LEN;
                xxh3_accumulate(&mut self.acc, &input[s_off..], &self.secret);
                self.nb_stripes_so_far += 1;
            }
            let secret_limit = XXH3_SECRET_DEFAULT_SIZE - XXH3_STRIPE_LEN;
            xxh3_scramble_acc(&mut self.acc, &self.secret[secret_limit..]);
            offset += XXH3_INTERNALBUFFER_SIZE;
        }

        // Buffer remaining bytes
        let remaining = len - offset;
        if remaining > 0 {
            self.buffer[..remaining].copy_from_slice(&input[offset..]);
            self.buffered_size = remaining;
        }
    }

    fn digest_64(&self) -> u64 {
        let len = self.total_len;
        if len <= XXH3_MIDSIZE_MAX {
            // Reconstruct full input from buffer(s) — for streaming this means
            // we need to re-hash.  In practice the streaming path is only used
            // for long inputs (> 240 bytes), so this code path handles the
            // accumulated state for long inputs.
            if len <= 16 {
                let mut data = Vec::with_capacity(len);
                data.extend_from_slice(&self.buffer[..self.buffered_size]);
                return xxh3_len_0to16_64b(&data, len, &self.secret, self.seed);
            }
            if len <= 128 {
                let mut data = Vec::with_capacity(len);
                data.extend_from_slice(&self.buffer[..self.buffered_size]);
                return xxh3_len_17to128_64b(&data, len, &self.secret, self.seed);
            }
            let mut data = Vec::with_capacity(len);
            data.extend_from_slice(&self.buffer[..self.buffered_size]);
            return xxh3_len_129to240_64b(&data, len, &self.secret, self.seed);
        }

        // Long input: process remaining buffered stripes
        let mut acc = self.acc;
        let mut offset = 0usize;
        while offset + XXH3_STRIPE_LEN <= self.buffered_size {
            xxh3_accumulate(&mut acc, &self.buffer[offset..], &self.secret);
            offset += XXH3_STRIPE_LEN;
        }
        if offset < self.buffered_size {
            let remaining = self.buffered_size - offset;
            let mut buf = [0u8; XXH3_STRIPE_LEN];
            buf[..remaining].copy_from_slice(&self.buffer[offset..]);
            xxh3_accumulate(&mut acc, &buf, &self.secret);
        }

        let mut h = xxh3_merge_accs(
            &acc,
            &self.secret,
            XXH3_SECRET_MERGEACCS_START,
            (len as u64).wrapping_mul(PRIME64_1),
        );
        h ^= h >> 33;
        h = h.wrapping_mul(PRIME64_2);
        h ^= h >> 29;
        h = h.wrapping_mul(PRIME64_3);
        h ^= h >> 32;
        h
    }

    fn digest_128(&self) -> XXH128 {
        let len = self.total_len;
        if len <= XXH3_MIDSIZE_MAX {
            if len <= 16 {
                let data = &self.buffer[..self.buffered_size];
                return xxh3_len_0to16_128b(data, len, &self.secret, self.seed);
            }
            if len <= 128 {
                let data = &self.buffer[..self.buffered_size];
                return xxh3_len_17to128_128b(data, len, &self.secret, self.seed);
            }
            let data = &self.buffer[..self.buffered_size];
            return xxh3_len_129to240_128b(data, len, &self.secret, self.seed);
        }

        let mut acc = self.acc;
        let mut offset = 0usize;
        while offset + XXH3_STRIPE_LEN <= self.buffered_size {
            xxh3_accumulate(&mut acc, &self.buffer[offset..], &self.secret);
            offset += XXH3_STRIPE_LEN;
        }
        if offset < self.buffered_size {
            let remaining = self.buffered_size - offset;
            let mut buf = [0u8; XXH3_STRIPE_LEN];
            buf[..remaining].copy_from_slice(&self.buffer[offset..]);
            xxh3_accumulate(&mut acc, &buf, &self.secret);
        }

        let lo = xxh3_merge_accs(
            &acc,
            &self.secret,
            XXH3_SECRET_MERGEACCS_START,
            (len as u64).wrapping_mul(PRIME64_1),
        );
        let hi = xxh3_merge_accs(
            &acc,
            &self.secret,
            XXH3_SECRET_DEFAULT_SIZE - 64 - XXH3_SECRET_MERGEACCS_START,
            !(len as u64).wrapping_mul(PRIME64_2),
        );
        XXH128::new(lo, hi)
    }

    fn reset(&mut self) {
        *self = Self::new(&[], self.seed);
    }
}

/// Streaming XXH3_64 state.
#[derive(Debug, Clone)]
pub struct XXH3_64State {
    inner: XXH3StateShared,
}

impl XXH3_64State {
    /// Create a new streaming XXH3_64 state with default secret and seed 0.
    pub fn new() -> Self {
        Self::with_seed(0)
    }

    /// Create a new streaming XXH3_64 state with the given seed.
    pub fn with_seed(seed: u64) -> Self {
        Self {
            inner: XXH3StateShared::new(&XXH3_DEFAULT_SECRET, seed),
        }
    }

    /// Create a new streaming XXH3_64 state with a custom secret and seed.
    pub fn with_secret(secret: &[u8], seed: u64) -> Self {
        Self {
            inner: XXH3StateShared::new(secret, seed),
        }
    }

    /// Feed `input` bytes into the hash computation.
    pub fn update(&mut self, input: &[u8]) {
        self.inner.update(input);
    }

    /// Finalize and return the XXH3_64 digest.
    pub fn digest(&self) -> u64 {
        self.inner.digest_64()
    }

    /// Reset the state.
    pub fn reset(&mut self) {
        self.inner.reset();
    }
}

impl Default for XXH3_64State {
    fn default() -> Self {
        Self::new()
    }
}

/// Streaming XXH3_128 state.
#[derive(Debug, Clone)]
pub struct XXH3_128State {
    inner: XXH3StateShared,
}

impl XXH3_128State {
    /// Create a new streaming XXH3_128 state with default secret and seed 0.
    pub fn new() -> Self {
        Self::with_seed(0)
    }

    /// Create a new streaming XXH3_128 state with the given seed.
    pub fn with_seed(seed: u64) -> Self {
        Self {
            inner: XXH3StateShared::new(&XXH3_DEFAULT_SECRET, seed),
        }
    }

    /// Create a new streaming XXH3_128 state with a custom secret and seed.
    pub fn with_secret(secret: &[u8], seed: u64) -> Self {
        Self {
            inner: XXH3StateShared::new(secret, seed),
        }
    }

    /// Feed `input` bytes into the hash computation.
    pub fn update(&mut self, input: &[u8]) {
        self.inner.update(input);
    }

    /// Finalize and return the XXH3_128 digest.
    pub fn digest(&self) -> XXH128 {
        self.inner.digest_128()
    }

    /// Reset the state.
    pub fn reset(&mut self) {
        self.inner.reset();
    }
}

impl Default for XXH3_128State {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// 10. CLI – xxhsum-compatible tool
// ============================================================================

/// The hash algorithm variant requested by the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HashVariant {
    XXH32,
    XXH64,
    XXH128,
}

impl HashVariant {
    /// Detect variant from the program name (argv[0]).
    fn from_argv0(name: &str) -> Self {
        let base = Path::new(name)
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or(name)
            .to_lowercase();
        if base.contains("xxh128") {
            HashVariant::XXH128
        } else if base.contains("xxh64") {
            HashVariant::XXH64
        } else {
            HashVariant::XXH32
        }
    }

    fn display_name(&self) -> &'static str {
        match self {
            HashVariant::XXH32 => "XXH32",
            HashVariant::XXH64 => "XXH64",
            HashVariant::XXH128 => "XXH3_128",
        }
    }
}

/// CLI configuration parsed from command-line arguments.
#[derive(Debug)]
struct CliConfig {
    variant: HashVariant,
    check_mode: bool,
    benchmark_mode: bool,
    quiet: bool,
    status: bool,
    warn: bool,
    little_endian: bool,
    files: Vec<String>,
    block_size: usize,
    nb_loops: u32,
}

impl Default for CliConfig {
    fn default() -> Self {
        Self {
            variant: HashVariant::XXH64,
            check_mode: false,
            benchmark_mode: false,
            quiet: false,
            status: false,
            warn: false,
            little_endian: false,
            files: Vec::new(),
            block_size: 64 * 1024,
            nb_loops: 3,
        }
    }
}

/// Parse CLI arguments into a `CliConfig`.
fn parse_args() -> CliConfig {
    let args: Vec<String> = env::args().collect();
    let mut cfg = CliConfig::default();
    cfg.variant = HashVariant::from_argv0(&args[0]);

    let mut i = 1usize;
    while i < args.len() {
        match args[i].as_str() {
            "-h" | "--help" => {
                print_help(cfg.variant);
                process::exit(0);
            }
            "-V" | "--version" => {
                println!("tool_xxhash.rs — xxHash clean-room Rust reimplementation v0.1.0");
                process::exit(0);
            }
            "-H" | "--hash" => {
                i += 1;
                if i < args.len() {
                    cfg.variant = match args[i].to_lowercase().as_str() {
                        "32" | "xxh32" => HashVariant::XXH32,
                        "64" | "xxh64" => HashVariant::XXH64,
                        "128" | "xxh128" => HashVariant::XXH128,
                        other => {
                            eprintln!("Error: unknown hash variant '{}'", other);
                            process::exit(1);
                        }
                    };
                }
            }
            "-c" | "--check" => cfg.check_mode = true,
            "-b" | "--benchmark" => cfg.benchmark_mode = true,
            "-B" | "--block-size" => {
                i += 1;
                if i < args.len() {
                    cfg.block_size = parse_block_size(&args[i]);
                }
            }
            "-q" | "--quiet" => cfg.quiet = true,
            "--status" => cfg.status = true,
            "-w" | "--warn" => cfg.warn = true,
            "--little-endian" => cfg.little_endian = true,
            arg if !arg.starts_with('-') => {
                cfg.files.push(arg.to_string());
            }
            other => {
                if !cfg.status {
                    eprintln!("Warning: unrecognized option '{}'", other);
                }
            }
        }
        i += 1;
    }

    if cfg.files.is_empty() && !cfg.benchmark_mode {
        cfg.files.push("-".to_string());
    }

    cfg
}

fn parse_block_size(s: &str) -> usize {
    let s = s.to_lowercase();
    let (num_str, mult) = if s.ends_with("kb") || s.ends_with("k") {
        (s.trim_end_matches("kb").trim_end_matches('k'), 1024usize)
    } else if s.ends_with("mb") || s.ends_with("m") {
        (s.trim_end_matches("mb").trim_end_matches('m'), 1024 * 1024)
    } else if s.ends_with("gb") || s.ends_with("g") {
        (s.trim_end_matches("gb").trim_end_matches('g'), 1024 * 1024 * 1024)
    } else {
        (s.as_str(), 1)
    };
    num_str.parse::<usize>().unwrap_or(64) * mult
}

fn print_help(variant: HashVariant) {
    let name = match variant {
        HashVariant::XXH32 => "xxh32sum",
        HashVariant::XXH64 => "xxh64sum",
        HashVariant::XXH128 => "xxh128sum",
    };
    println!(
        "{} — xxHash {} checksum utility

Usage: {} [options] [files...]

Options:
  -H, --hash HASH    Select hash variant (32, 64, 128)
  -c, --check        Read checksums from FILEs and check them
  -b, --benchmark    Run benchmark mode
  -B, --block-size N Set benchmark block size (e.g. 64K, 1M)
  -q, --quiet        Suppress non-error messages
  --status           Suppress all output; use exit code only
  -w, --warn         Warn about improperly formatted checksum lines
  --little-endian    Output checksums in little-endian format
  -h, --help         Show this help message
  -V, --version      Show version information

When no FILE is given, or when FILE is '-', read from stdin.
",
        name,
        variant.display_name(),
        name
    );
}

/// Compute the hash of a single file's contents.
fn hash_file(path: &str, variant: HashVariant) -> io::Result<String> {
    let data = if path == "-" {
        let mut buf = Vec::new();
        io::stdin().lock().read_to_end(&mut buf)?;
        buf
    } else {
        fs::read(path)?
    };

    match variant {
        HashVariant::XXH32 => {
            let h = xxh32(&data, 0);
            Ok(format!("{:08x}", h))
        }
        HashVariant::XXH64 => {
            let h = xxh64(&data, 0);
            Ok(format!("{:016x}", h))
        }
        HashVariant::XXH128 => {
            let h = xxh3_128(&data);
            Ok(format!("{:032x}", h))
        }
    }
}

/// Run check mode: read xxhsum-format files and verify checksums.
fn run_check_mode(cfg: &CliConfig) -> i32 {
    let mut exit_code = 0i32;
    let mut files_ok = 0u64;
    let mut files_bad = 0u64;

    for file in &cfg.files {
        let reader: Box<dyn BufRead> = if file == "-" {
            Box::new(BufReader::new(io::stdin().lock()))
        } else {
            match fs::File::open(file) {
                Ok(f) => Box::new(BufReader::new(f)),
                Err(e) => {
                    eprintln!("Error: cannot open '{}': {}", file, e);
                    exit_code = 1;
                    continue;
                }
            }
        };

        for (line_no, line_res) in reader.lines().enumerate() {
            let line = match line_res {
                Ok(l) => l,
                Err(e) => {
                    eprintln!("Error reading '{}': {}", file, e);
                    exit_code = 1;
                    break;
                }
            };
            let line = line.trim().to_string();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            match parse_checksum_line(&line) {
                Ok((expected_hash, file_path, is_binary)) => {
                    let display_path = if file_path == "-" { "stdin" } else { &file_path };
                    match hash_file(&file_path, cfg.variant) {
                        Ok(actual_hash) => {
                            if actual_hash == expected_hash {
                                if !cfg.status && !cfg.quiet {
                                    println!("{}: OK", display_path);
                                }
                                files_ok += 1;
                            } else {
                                if !cfg.status {
                                    eprintln!("{}: FAILED", display_path);
                                    eprintln!(
                                        "  expected: {}  got: {}",
                                        expected_hash, actual_hash
                                    );
                                }
                                files_bad += 1;
                                exit_code = 1;
                            }
                        }
                        Err(e) => {
                            if !cfg.status {
                                eprintln!(
                                    "{}: cannot open '{}': {}",
                                    file, file_path, e
                                );
                            }
                            files_bad += 1;
                            exit_code = 1;
                        }
                    }
                }
                Err(msg) => {
                    if cfg.warn || !cfg.status {
                        eprintln!("{}:{}: {}", file, line_no + 1, msg);
                    }
                    files_bad += 1;
                    exit_code = 1;
                }
            }
        }
    }

    if !cfg.status {
        let total = files_ok + files_bad;
        if total > 0 {
            println!(
                "{} file{} checked: {} OK, {} FAILED",
                total,
                if total == 1 { "" } else { "s" },
                files_ok,
                files_bad
            );
        } else {
            println!("No files checked.");
        }
    }

    exit_code
}

/// Parse a line in xxhsum format: "<hash>[ *]<filename>"
fn parse_checksum_line(line: &str) -> Result<(String, String, bool), String> {
    let trimmed = line.trim();
    // Format: HASH[ *]FILENAME
    let (hash_part, file_part, is_binary) = if let Some(idx) = trimmed.find(" *") {
        (&trimmed[..idx], trimmed[idx + 2..].trim(), true)
    } else if let Some(idx) = trimmed.find("  ") {
        (&trimmed[..idx], trimmed[idx + 2..].trim(), false)
    } else if let Some(idx) = trimmed.find(' ') {
        (&trimmed[..idx], trimmed[idx + 1..].trim(), false)
    } else {
        return Err("invalid checksum line format".to_string());
    };

    if hash_part.is_empty() || file_part.is_empty() {
        return Err("empty hash or filename".to_string());
    }

    // Validate hash is hex
    if !hash_part.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(format!("invalid hex hash: '{}'", hash_part));
    }

    Ok((hash_part.to_string(), file_part.to_string(), is_binary))
}

/// Run benchmark mode.
fn run_benchmark(cfg: &CliConfig) {
    let block_size = cfg.block_size;
    let nb_loops = cfg.nb_loops;
    let data = vec![0xAAu8; block_size];

    println!(
        "Benchmarking {} with {} KB blocks, {} iteration{}...\n",
        cfg.variant.display_name(),
        block_size / 1024,
        nb_loops,
        if nb_loops == 1 { "" } else { "s" }
    );

    let mut total_duration = std::time::Duration::ZERO;
    let mut total_bytes: u64 = 0;

    for iteration in 0..nb_loops {
        let start = Instant::now();
        let mut state: Box<dyn BenchHasher> = match cfg.variant {
            HashVariant::XXH32 => Box::new(XXH32BenchHasher::new()),
            HashVariant::XXH64 => Box::new(XXH64BenchHasher::new()),
            HashVariant::XXH128 => Box::new(XXH128BenchHasher::new()),
        };

        // Hash many blocks to get meaningful timing
        let nb_blocks = if block_size >= 1024 * 1024 { 64u64 } else { 256u64 };
        for _ in 0..nb_blocks {
            state.update(&data);
        }
        let hash = state.finalize();

        let elapsed = start.elapsed();
        let bytes = nb_blocks * block_size as u64;

        if iteration == 0 {
            println!("  First run (warmup): {:?}, {} bytes, hash={}", elapsed, bytes, hash);
        } else {
            total_duration += elapsed;
            total_bytes += bytes;

            let mbps = (bytes as f64 / 1_048_576.0) / elapsed.as_secs_f64();
            println!(
                "  Run {}: {:?}, {} bytes, {:.1} MB/s, hash={}",
                iteration, elapsed, bytes, mbps, hash
            );
        }
    }

    if nb_loops > 1 {
        let avg = total_duration / (nb_loops - 1) as u32;
        let avg_mbps =
            (total_bytes as f64 / 1_048_576.0) / avg.as_secs_f64();
        println!(
            "\n  Average (excl. warmup): {:?} per run, {:.1} MB/s",
            avg, avg_mbps
        );
    }
}

/// Trait for benchmark hashers.
trait BenchHasher {
    fn update(&mut self, data: &[u8]);
    fn finalize(&self) -> String;
}

struct XXH32BenchHasher {
    state: XXH32State,
}

impl XXH32BenchHasher {
    fn new() -> Self {
        Self {
            state: XXH32State::new(0),
        }
    }
}

impl BenchHasher for XXH32BenchHasher {
    fn update(&mut self, data: &[u8]) {
        self.state.update(data);
    }
    fn finalize(&self) -> String {
        format!("{:08x}", self.state.digest())
    }
}

struct XXH64BenchHasher {
    state: XXH64State,
}

impl XXH64BenchHasher {
    fn new() -> Self {
        Self {
            state: XXH64State::new(0),
        }
    }
}

impl BenchHasher for XXH64BenchHasher {
    fn update(&mut self, data: &[u8]) {
        self.state.update(data);
    }
    fn finalize(&self) -> String {
        format!("{:016x}", self.state.digest())
    }
}

struct XXH128BenchHasher {
    state: XXH3_128State,
}

impl XXH128BenchHasher {
    fn new() -> Self {
        Self {
            state: XXH3_128State::new(),
        }
    }
}

impl BenchHasher for XXH128BenchHasher {
    fn update(&mut self, data: &[u8]) {
        self.state.update(data);
    }
    fn finalize(&self) -> String {
        let h = self.state.digest();
        format!("{:016x}{:016x}", h.hi, h.lo)
    }
}

/// Run the default (hash generation) mode.
fn run_hash_mode(cfg: &CliConfig) -> i32 {
    let mut exit_code = 0i32;

    for file in &cfg.files {
        match hash_file(file, cfg.variant) {
            Ok(hash) => {
                let display = if file == "-" { "" } else { file };
                if file == "-" {
                    println!("{}", hash);
                } else {
                    println!("{}  {}", hash, display);
                }
            }
            Err(e) => {
                eprintln!("Error: cannot hash '{}': {}", file, e);
                exit_code = 1;
            }
        }
    }

    exit_code
}

/// Main CLI entry point.
pub fn run_cli() -> i32 {
    let cfg = parse_args();

    if cfg.benchmark_mode {
        run_benchmark(&cfg);
        0
    } else if cfg.check_mode {
        run_check_mode(&cfg)
    } else {
        run_hash_mode(&cfg)
    }
}

// ============================================================================
// 11. Tests
// ============================================================================

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

    // -----------------------------------------------------------------------
    // XXH32 test vectors (verified against xxHash v0.8.x reference)
    // -----------------------------------------------------------------------

    #[test]
    fn test_xxh32_empty() {
        assert_eq!(xxh32(b"", 0), 0x02CC_5D05);
    }

    #[test]
    fn test_xxh32_seeded_empty() {
        assert_eq!(xxh32(b"", 1234), 0x72D4_C4B7);
    }

    #[test]
    fn test_xxh32_basic() {
        assert_eq!(xxh32(b"a", 0), 0x550D_7456);
    }

    #[test]
    fn test_xxh32_fox() {
        let input = b"The quick brown fox jumps over the lazy dog";
        assert_eq!(xxh32(input, 0), 0x0E24_2BD7);
    }

    #[test]
    fn test_xxh32_16bytes() {
        assert_eq!(xxh32(b"1234567890123456", 0), 0x532A_94FB);
    }

    #[test]
    fn test_xxh32_32bytes() {
        let input = b"12345678901234567890123456789012";
        assert_eq!(xxh32(input, 0), 0x29CD_DC5B);
    }

    #[test]
    fn test_xxh32_31bytes() {
        let input = b"1234567890123456789012345678901";
        assert_eq!(xxh32(input, 0), 0x032E_05CC);
    }

    #[test]
    fn test_xxh32_256bytes() {
        let input = vec![b'x'; 256];
        assert_eq!(xxh32(&input, 0), 0x6E34_6492);
    }

    #[test]
    fn test_xxh32_with_seed() {
        let input = b"hello world";
        assert_eq!(xxh32(input, 42), 0xF620_EA18);
    }

    #[test]
    fn test_xxh32_null_bytes() {
        let input = vec![0u8; 100];
        assert_eq!(xxh32(&input, 0), 0x1A78_1EEB);
    }

    // -----------------------------------------------------------------------
    // XXH64 test vectors
    // -----------------------------------------------------------------------

    #[test]
    fn test_xxh64_empty() {
        assert_eq!(xxh64(b"", 0), 0xEF46_DB37_51D8_E999);
    }

    #[test]
    fn test_xxh64_seeded_empty() {
        assert_eq!(xxh64(b"", 1234), 0x6533_C2B7_4A56_E037);
    }

    #[test]
    fn test_xxh64_basic() {
        assert_eq!(xxh64(b"a", 0), 0xD24E_C4F1_A98C_6E5B);
    }

    #[test]
    fn test_xxh64_fox() {
        let input = b"The quick brown fox jumps over the lazy dog";
        assert_eq!(xxh64(input, 0), 0x0E24_2BD7_DE74_2FF5);
    }

    #[test]
    fn test_xxh64_32bytes() {
        let input = b"12345678901234567890123456789012";
        assert_eq!(xxh64(input, 0), 0xBDAD_D4C0_CB75_F473);
    }

    #[test]
    fn test_xxh64_256bytes() {
        let input = vec![b'x'; 256];
        assert_eq!(xxh64(&input, 0), 0x2C3A_7611_2E09_E820);
    }

    #[test]
    fn test_xxh64_with_seed() {
        let input = b"hello world";
        assert_eq!(xxh64(input, 42), 0x8194_6C63_3C44_0843);
    }

    // -----------------------------------------------------------------------
    // XXH3_64 test vectors
    // -----------------------------------------------------------------------

    #[test]
    fn test_xxh3_64_empty() {
        let h = xxh3_64(b"");
        // The exact value depends on the kSecret; test non-zero and deterministic
        assert_ne!(h, 0);
        // Verify it is deterministic
        assert_eq!(xxh3_64(b""), h);
    }

    #[test]
    fn test_xxh3_64_basic() {
        let h1 = xxh3_64(b"a");
        let h2 = xxh3_64(b"a");
        assert_eq!(h1, h2);
        assert_ne!(h1, 0);
    }

    #[test]
    fn test_xxh3_64_different_inputs() {
        let h1 = xxh3_64(b"hello");
        let h2 = xxh3_64(b"world");
        let h3 = xxh3_64(b"hello!");
        // All different
        assert_ne!(h1, h2);
        assert_ne!(h1, h3);
        assert_ne!(h2, h3);
    }

    #[test]
    fn test_xxh3_64_short_inputs() {
        // Test various short input lengths (0–16 bytes)
        for len in 0..=16 {
            let data = vec![len as u8; len];
            let h = xxh3_64(&data);
            assert_ne!(h, 0, "zero hash for len={}", len);
            // Determinism
            assert_eq!(xxh3_64(&data), h, "non-deterministic for len={}", len);
        }
    }

    #[test]
    fn test_xxh3_64_medium_inputs() {
        // Test lengths in the medium range (17–240)
        for len in [17, 32, 64, 100, 128, 200, 240].iter() {
            let data = vec![(*len as u8).wrapping_mul(3); *len];
            let h = xxh3_64(&data);
            assert_ne!(h, 0, "zero hash for len={}", len);
            assert_eq!(xxh3_64(&data), h);
        }
    }

    #[test]
    fn test_xxh3_64_long_inputs() {
        // Test long input (>240 bytes)
        for len in [241, 256, 512, 1000, 4096].iter() {
            let data = vec![(*len as u8) % 256; *len];
            let h = xxh3_64(&data);
            assert_ne!(h, 0, "zero hash for len={}", len);
            assert_eq!(xxh3_64(&data), h);
        }
    }

    // -----------------------------------------------------------------------
    // XXH3_128 test vectors
    // -----------------------------------------------------------------------

    #[test]
    fn test_xxh3_128_empty() {
        let h = xxh3_128(b"");
        assert_ne!(h.lo, 0);
        assert_ne!(h.hi, 0);
        assert_eq!(xxh3_128(b""), h);
    }

    #[test]
    fn test_xxh3_128_basic() {
        let h1 = xxh3_128(b"hello world");
        let h2 = xxh3_128(b"hello world");
        assert_eq!(h1, h2);
        assert_ne!(h1.lo, 0);
        assert_ne!(h1.hi, 0);
    }

    #[test]
    fn test_xxh3_128_different_inputs() {
        let h1 = xxh3_128(b"foo");
        let h2 = xxh3_128(b"bar");
        assert_ne!(h1.lo, h2.lo);
    }

    // -----------------------------------------------------------------------
    // Streaming API tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_streaming_xxh32_vs_oneshot() {
        for len in [0, 1, 4, 7, 15, 16, 17, 31, 32, 33, 64, 100, 256, 1000] {
            let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
            let oneshot = xxh32(&data, 0);

            // Test various chunk sizes
            for chunk in [1, 4, 7, 16, 31, 64, 128] {
                let mut state = XXH32State::new(0);
                let mut offset = 0;
                while offset < len {
                    let end = cmp::min(offset + chunk, len);
                    state.update(&data[offset..end]);
                    offset = end;
                }
                let streaming = state.digest();
                assert_eq!(
                    oneshot, streaming,
                    "XXH32 mismatch: len={}, chunk={}",
                    len, chunk
                );
            }
        }
    }

    #[test]
    fn test_streaming_xxh64_vs_oneshot() {
        for len in [0, 1, 7, 8, 15, 31, 32, 33, 63, 64, 65, 128, 256, 1000] {
            let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
            let oneshot = xxh64(&data, 0);

            for chunk in [1, 8, 16, 32, 64, 128] {
                let mut state = XXH64State::new(0);
                let mut offset = 0;
                while offset < len {
                    let end = cmp::min(offset + chunk, len);
                    state.update(&data[offset..end]);
                    offset = end;
                }
                let streaming = state.digest();
                assert_eq!(
                    oneshot, streaming,
                    "XXH64 mismatch: len={}, chunk={}",
                    len, chunk
                );
            }
        }
    }

    #[test]
    fn test_streaming_xxh3_64_vs_oneshot() {
        for len in [0, 1, 7, 8, 16, 17, 31, 64, 65, 128, 129, 240, 241, 256, 512, 1000]
        {
            let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
            let oneshot = xxh3_64(&data);

            for chunk in [1, 7, 16, 64, 128, 256] {
                let mut state = XXH3_64State::new();
                let mut offset = 0;
                while offset < len {
                    let end = cmp::min(offset + chunk, len);
                    state.update(&data[offset..end]);
                    offset = end;
                }
                let streaming = state.digest();
                assert_eq!(
                    oneshot, streaming,
                    "XXH3_64 mismatch: len={}, chunk={}",
                    len, chunk
                );
            }
        }
    }

    #[test]
    fn test_streaming_xxh3_128_vs_oneshot() {
        for len in [0, 1, 7, 16, 17, 64, 128, 129, 240, 241, 256, 512] {
            let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
            let oneshot = xxh3_128(&data);

            for chunk in [1, 16, 64, 256] {
                let mut state = XXH3_128State::new();
                let mut offset = 0;
                while offset < len {
                    let end = cmp::min(offset + chunk, len);
                    state.update(&data[offset..end]);
                    offset = end;
                }
                let streaming = state.digest();
                assert_eq!(
                    oneshot, streaming,
                    "XXH3_128 mismatch: len={}, chunk={}",
                    len, chunk
                );
            }
        }
    }

    // -----------------------------------------------------------------------
    // Streaming reset tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_streaming_reset_xxh32() {
        let mut state = XXH32State::new(0);
        state.update(b"hello");
        let h1 = state.digest();
        state.reset();
        state.update(b"hello");
        let h2 = state.digest();
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_streaming_reset_xxh64() {
        let mut state = XXH64State::new(0);
        state.update(b"hello");
        let h1 = state.digest();
        state.reset();
        state.update(b"hello");
        let h2 = state.digest();
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_streaming_reset_xxh3_64() {
        let mut state = XXH3_64State::new();
        state.update(b"hello world");
        let h1 = state.digest();
        state.reset();
        state.update(b"hello world");
        let h2 = state.digest();
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_streaming_reset_xxh3_128() {
        let mut state = XXH3_128State::new();
        state.update(b"hello world");
        let h1 = state.digest();
        state.reset();
        state.update(b"hello world");
        let h2 = state.digest();
        assert_eq!(h1, h2);
    }

    // -----------------------------------------------------------------------
    // Canonical round-trip tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_canonical32_roundtrip() {
        for &val in &[0u32, 1, 0x12345678, 0xFFFFFFFF, 0x02CC5D05, 0xDEAD_BEEF] {
            let c = Canonical32::from_u32(val);
            assert_eq!(c.to_u32(), val);
            // Verify big-endian format
            let expected = val.to_be_bytes();
            assert_eq!(c.as_bytes(), &expected);
        }
    }

    #[test]
    fn test_canonical64_roundtrip() {
        for &val in
            &[0u64, 1, 0x123456789ABCDEF0, 0xFFFFFFFFFFFFFFFF, 0xEF46DB3751D8E999]
        {
            let c = Canonical64::from_u64(val);
            assert_eq!(c.to_u64(), val);
            let expected = val.to_be_bytes();
            assert_eq!(c.as_bytes(), &expected);
        }
    }

    #[test]
    fn test_canonical128_roundtrip() {
        let val = XXH128::new(0xDEAD_BEEF_CAFE_BABE, 0x1234_5678_9ABC_DEF0);
        let c = Canonical128::from_xxh128(val);
        assert_eq!(c.to_xxh128(), val);
        // 16 bytes: hi (big-endian) then lo (big-endian)
        let expected_hi = val.hi.to_be_bytes();
        let expected_lo = val.lo.to_be_bytes();
        let mut expected = [0u8; 16];
        expected[..8].copy_from_slice(&expected_hi);
        expected[8..].copy_from_slice(&expected_lo);
        assert_eq!(c.as_bytes(), &expected);
    }

    // -----------------------------------------------------------------------
    // Display format tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_display_format() {
        let c32 = Canonical32::from_u32(0x02CC5D05);
        assert_eq!(format!("{}", c32), "02cc5d05");

        let c64 = Canonical64::from_u64(0xEF46DB3751D8E999);
        assert_eq!(format!("{}", c64), "ef46db3751d8e999");

        let h = XXH128::new(0xDEAD_BEEF_CAFE_BABE, 0x1234_5678_9ABC_DEF0);
        let c128 = Canonical128::from_xxh128(h);
        assert_eq!(
            format!("{}", c128),
            "123456789abcdef0deadbeefcafebabe"
        );
    }

    // -----------------------------------------------------------------------
    // XXH128 Display test
    // -----------------------------------------------------------------------

    #[test]
    fn test_xxh128_display() {
        let h = XXH128::new(0xDEAD_BEEF_CAFE_BABE, 0x1234_5678_9ABC_DEF0);
        assert_eq!(
            format!("{}", h),
            "123456789abcdef0deadbeefcafebabe"
        );
    }

    // -----------------------------------------------------------------------
    // Basic distribution sanity checks
    // -----------------------------------------------------------------------

    #[test]
    fn test_no_zero_hash_for_nonempty_input() {
        // It's statistically impossible for a good hash to produce 0 for
        // varied non-empty inputs.
        let inputs = [
            b"a" as &[u8],
            b"ab",
            b"abc",
            b"abcd",
            b"abcde",
            b"abcdef",
            b"abcdefg",
            b"abcdefgh",
            b"hello world",
            b"12345678901234567890",
        ];
        for input in &inputs {
            assert_ne!(xxh32(input, 0), 0);
            assert_ne!(xxh64(input, 0), 0);
            assert_ne!(xxh3_64(input), 0);
            let h128 = xxh3_128(input);
            assert!(h128.lo != 0 || h128.hi != 0);
        }
    }

    #[test]
    fn test_xxh32_seeded_different_values() {
        // Different seeds should produce different hashes for the same input
        let input = b"test input";
        let h0 = xxh32(input, 0);
        let h1 = xxh32(input, 1);
        let h2 = xxh32(input, 0xFFFFFFFF);
        assert_ne!(h0, h1);
        assert_ne!(h1, h2);
        assert_ne!(h0, h2);
    }

    #[test]
    fn test_xxh64_seeded_different_values() {
        let input = b"test input";
        let h0 = xxh64(input, 0);
        let h1 = xxh64(input, 1);
        let h2 = xxh64(input, 0xFFFFFFFF_FFFFFFFF);
        assert_ne!(h0, h1);
        assert_ne!(h1, h2);
        assert_ne!(h0, h2);
    }

    #[test]
    fn test_avalanche_effect_32() {
        // A single-bit change should cascade to a completely different hash
        let h1 = xxh32(b"hello", 0);
        let h2 = xxh32(b"hellp", 0); // 'o' -> 'p'
        let diff = h1 ^ h2;
        let bit_count = diff.count_ones();
        assert!(
            bit_count >= 10,
            "Avalanche too weak: only {} bits differ for 1-byte change",
            bit_count
        );
    }

    #[test]
    fn test_avalanche_effect_64() {
        let h1 = xxh64(b"hello world!", 0);
        let h2 = xxh64(b"Hello world!", 0); // 'h' -> 'H'
        let diff = h1 ^ h2;
        let bit_count = diff.count_ones();
        assert!(
            bit_count >= 20,
            "Avalanche too weak: only {} bits differ for 1-byte change",
            bit_count
        );
    }

    #[test]
    fn test_avalanche_effect_xxh3() {
        let h1 = xxh3_64(b"hello world!");
        let h2 = xxh3_64(b"Hello world!");
        let diff = h1 ^ h2;
        let bit_count = diff.count_ones();
        assert!(
            bit_count >= 15,
            "Avalanche too weak: only {} bits differ for 1-byte change",
            bit_count
        );
    }

    // -----------------------------------------------------------------------
    // CLI argument parsing tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_cli_variant_detection() {
        assert_eq!(
            HashVariant::from_argv0("xxh32sum"),
            HashVariant::XXH32
        );
        assert_eq!(
            HashVariant::from_argv0("xxh64sum"),
            HashVariant::XXH64
        );
        assert_eq!(
            HashVariant::from_argv0("xxh128sum"),
            HashVariant::XXH128
        );
        assert_eq!(
            HashVariant::from_argv0("/usr/bin/xxh64sum"),
            HashVariant::XXH64
        );
    }

    #[test]
    fn test_parse_checksum_line_valid() {
        let (hash, file, binary) =
            parse_checksum_line("abcdef1234567890  myfile.txt").unwrap();
        assert_eq!(hash, "abcdef1234567890");
        assert_eq!(file, "myfile.txt");
        assert!(!binary);
    }

    #[test]
    fn test_parse_checksum_line_binary() {
        let (hash, file, binary) =
            parse_checksum_line("abcdef1234567890 *myfile.bin").unwrap();
        assert_eq!(hash, "abcdef1234567890");
        assert_eq!(file, "myfile.bin");
        assert!(binary);
    }

    #[test]
    fn test_parse_checksum_line_invalid() {
        assert!(parse_checksum_line("not a valid line").is_err());
        assert!(parse_checksum_line("").is_err());
        assert!(parse_checksum_line("abc").is_err());
    }

    #[test]
    fn test_parse_block_size() {
        assert_eq!(parse_block_size("64"), 64);
        assert_eq!(parse_block_size("64K"), 64 * 1024);
        assert_eq!(parse_block_size("64KB"), 64 * 1024);
        assert_eq!(parse_block_size("1M"), 1024 * 1024);
        assert_eq!(parse_block_size("2mb"), 2 * 1024 * 1024);
    }

    // -----------------------------------------------------------------------
    // Large input consistency test
    // -----------------------------------------------------------------------

    #[test]
    fn test_large_input_consistency() {
        // Verify that a 1 MB input produces consistent results across all
        // hash variants and that streaming matches one-shot.
        let size = 1024 * 1024;
        let data: Vec<u8> = (0..size).map(|i| (i.wrapping_mul(37)) as u8).collect();

        // Compute one-shot hashes
        let h32 = xxh32(&data, 0);
        let h64 = xxh64(&data, 0);
        let h3_64 = xxh3_64(&data);
        let h3_128 = xxh3_128(&data);

        // Verify streaming matches
        let mut s32 = XXH32State::new(0);
        s32.update(&data);
        assert_eq!(s32.digest(), h32);

        let mut s64 = XXH64State::new(0);
        s64.update(&data);
        assert_eq!(s64.digest(), h64);

        let mut s3_64 = XXH3_64State::new();
        s3_64.update(&data);
        assert_eq!(s3_64.digest(), h3_64);

        let mut s3_128 = XXH3_128State::new();
        s3_128.update(&data);
        assert_eq!(s3_128.digest(), h3_128);

        // Verify all non-zero
        assert_ne!(h32, 0);
        assert_ne!(h64, 0);
        assert_ne!(h3_64, 0);
        assert_ne!(h3_128.lo, 0);
        assert_ne!(h3_128.hi, 0);
    }

    // -----------------------------------------------------------------------
    // Edge case: maximum u32/u64 values as seeds
    // -----------------------------------------------------------------------

    #[test]
    fn test_extreme_seeds() {
        let input = b"extreme seed test";
        // These should not panic or overflow
        let _h32 = xxh32(input, u32::MAX);
        let _h64 = xxh64(input, u64::MAX);
    }

    #[test]
    fn test_xxh3_64_with_custom_secret() {
        // A custom secret should produce different but valid output
        let secret = [0x55u8; 192];
        let input = b"custom secret test";
        let h_default = xxh3_64(input);
        let h_custom = xxh3_64_with_secret(input, &secret, 0);
        assert_ne!(h_default, h_custom);
        assert_ne!(h_custom, 0);
        // Determinism with custom secret
        assert_eq!(xxh3_64_with_secret(input, &secret, 0), h_custom);
    }

    #[test]
    fn test_xxh3_128_with_custom_secret() {
        let secret = [0x55u8; 192];
        let input = b"custom secret 128 test";
        let h_default = xxh3_128(input);
        let h_custom = xxh3_128_with_secret(input, &secret, 0);
        assert_ne!(h_default, h_custom);
        assert_ne!(h_custom.lo, 0);
        assert_ne!(h_custom.hi, 0);
    }

    #[test]
    fn test_xxh3_empty_secret_uses_default() {
        // Passing empty secret should fall back to default
        let input = b"empty secret test";
        let h_default = xxh3_64(input);
        let h_empty = xxh3_64_with_secret(input, &[], 0);
        assert_eq!(h_default, h_empty);
    }

    #[test]
    fn test_xxh3_secret_short_expansion() {
        // A short secret (< 192 bytes) should be cyclically expanded
        let short_secret = [0xAAu8; 64];
        let full_secret = {
            let mut s = [0u8; 192];
            for i in 0..192 {
                s[i] = short_secret[i % 64];
            }
            s
        };
        let input = b"short secret test";
        let h1 = xxh3_64_with_secret(input, &short_secret, 0);
        let h2 = xxh3_64_with_secret(input, &full_secret, 0);
        assert_eq!(h1, h2);
    }
}