libzstd-rs-sys 0.0.0

a rust implementation of zstd compression and decompression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
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
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
use core::ptr;

use libc::{calloc, free, malloc, size_t};

use crate::lib::common::entropy_common::FSE_readNCount_slice;
use crate::lib::common::error_private::{ERR_isError, Error};
use crate::lib::common::mem::MEM_readLE32;
use crate::lib::common::xxhash::{
    ZSTD_XXH64_digest, ZSTD_XXH64_reset, ZSTD_XXH64_slice, ZSTD_XXH64_update,
};
use crate::lib::common::zstd_common::ZSTD_getErrorCode;
use crate::lib::common::zstd_internal::{
    repStartValue, LL_bits, ML_bits, MaxLL, MaxML, MaxOff, ZSTD_blockHeaderSize,
    ZSTD_cpuSupportsBmi2, ZSTD_limitCopy, WILDCOPY_OVERLENGTH, ZSTD_FRAMEIDSIZE,
    ZSTD_WORKSPACETOOLARGE_FACTOR, ZSTD_WORKSPACETOOLARGE_MAXDURATION,
};
use crate::lib::compress::zstd_compress::{ZSTD_CCtx_params_s, ZSTD_CCtx_s};
use crate::lib::decompress::huf_decompress::{
    DTableDesc, HUF_ReadDTableX2_Workspace, HUF_readDTableX2_wksp,
};
use crate::lib::decompress::zstd_ddict::{MultipleDDicts, ZSTD_DDict, ZSTD_DDictHashSet};
use crate::lib::decompress::zstd_decompress_block::{
    getc_block_size, ZSTD_buildFSETable, ZSTD_checkContinuity, ZSTD_decompressBlock_internal,
    ZSTD_getcBlockSize,
};
use crate::lib::decompress::{
    blockProperties_t, BlockType, DecompressStage, LL_base, ML_base, NextInputType, OF_base,
    OF_bits, StreamStage, ZSTD_DCtx, ZSTD_DCtx_s, ZSTD_FrameHeader, ZSTD_d_ignoreChecksum,
    ZSTD_d_validateChecksum, ZSTD_dont_use, ZSTD_entropyDTables_t, ZSTD_forceIgnoreChecksum_e,
    ZSTD_frame, ZSTD_skippableFrame, ZSTD_use_indefinitely, ZSTD_use_once,
};
use crate::lib::zstd::experimental::ZSTD_FRAMEHEADERSIZE_MIN;
use crate::lib::zstd::*;

use crate::lib::common::zstd_trace::{
    ZSTD_Trace, ZSTD_trace_decompress_begin, ZSTD_trace_decompress_end,
};

use crate::lib::legacy::zstd_v05::{
    ZBUFFv05_DCtx, ZBUFFv05_createDCtx, ZBUFFv05_decompressContinue,
    ZBUFFv05_decompressInitDictionary, ZBUFFv05_freeDCtx, ZSTDv05_createDCtx,
    ZSTDv05_decompress_usingDict, ZSTDv05_fast, ZSTDv05_findFrameSizeInfoLegacy, ZSTDv05_freeDCtx,
    ZSTDv05_getFrameParams, ZSTDv05_parameters,
};
use crate::lib::legacy::zstd_v06::{
    ZBUFFv06_DCtx_s, ZBUFFv06_createDCtx, ZBUFFv06_decompressContinue,
    ZBUFFv06_decompressInitDictionary, ZBUFFv06_freeDCtx, ZSTDv06_createDCtx,
    ZSTDv06_decompress_usingDict, ZSTDv06_findFrameSizeInfoLegacy, ZSTDv06_frameParams_s,
    ZSTDv06_freeDCtx, ZSTDv06_getFrameParams,
};
use crate::lib::legacy::zstd_v07::{
    ZBUFFv07_DCtx_s, ZBUFFv07_createDCtx, ZBUFFv07_decompressContinue,
    ZBUFFv07_decompressInitDictionary, ZBUFFv07_freeDCtx, ZSTDv07_createDCtx,
    ZSTDv07_decompress_usingDict, ZSTDv07_findFrameSizeInfoLegacy, ZSTDv07_frameParams,
    ZSTDv07_freeDCtx, ZSTDv07_getFrameParams,
};

use crate::lib::decompress::zstd_ddict::{
    ZSTD_DDict_dictContent, ZSTD_DDict_dictSize, ZSTD_copyDDictParameters,
    ZSTD_createDDict_advanced, ZSTD_freeDDict, ZSTD_getDictID_fromDDict, ZSTD_sizeof_DDict,
};

pub type ZSTD_outBuffer = ZSTD_outBuffer_s;
#[repr(C)]
pub struct ZSTD_cpuid_t {
    pub f1c: u32,
    pub f1d: u32,
    pub f7b: u32,
    pub f7c: u32,
}
type ZBUFFv07_DCtx = ZBUFFv07_DCtx_s;
type ZBUFFv06_DCtx = ZBUFFv06_DCtx_s;
type XXH_errorcode = core::ffi::c_uint;
pub const XXH_ERROR: XXH_errorcode = 1;
pub const XXH_OK: XXH_errorcode = 0;
pub type streaming_operation = core::ffi::c_uint;
pub const is_streaming: streaming_operation = 1;
pub const not_streaming: streaming_operation = 0;
#[repr(C)]
pub struct ZSTD_frameSizeInfo {
    pub nbBlocks: size_t,
    pub compressedSize: size_t,
    pub decompressedBound: core::ffi::c_ulonglong,
}
#[repr(C)]
pub struct ZSTD_bounds {
    pub error: size_t,
    pub lowerBound: core::ffi::c_int,
    pub upperBound: core::ffi::c_int,
}
pub type ZSTD_ResetDirective = core::ffi::c_uint;
pub const ZSTD_reset_session_and_parameters: ZSTD_ResetDirective = 3;
pub const ZSTD_reset_parameters: ZSTD_ResetDirective = 2;
pub const ZSTD_reset_session_only: ZSTD_ResetDirective = 1;
pub type ZSTD_dParameter = core::ffi::c_uint;
pub const ZSTD_d_experimentalParam6: ZSTD_dParameter = 1005;
pub const ZSTD_d_experimentalParam5: ZSTD_dParameter = 1004;
pub const ZSTD_d_experimentalParam4: ZSTD_dParameter = 1003;
pub const ZSTD_d_experimentalParam3: ZSTD_dParameter = 1002;
pub const ZSTD_d_experimentalParam2: ZSTD_dParameter = 1001;
pub const ZSTD_d_experimentalParam1: ZSTD_dParameter = 1000;
pub const ZSTD_d_windowLogMax: ZSTD_dParameter = 100;
pub type ZSTD_DStream = ZSTD_DCtx;
pub type ZSTD_nextInputType_e = core::ffi::c_uint;
pub const ZSTDnit_skippableFrame: ZSTD_nextInputType_e = 5;
pub const ZSTDnit_checksum: ZSTD_nextInputType_e = 4;
pub const ZSTDnit_lastBlock: ZSTD_nextInputType_e = 3;
pub const ZSTDnit_block: ZSTD_nextInputType_e = 2;
pub const ZSTDnit_blockHeader: ZSTD_nextInputType_e = 1;
pub const ZSTDnit_frameHeader: ZSTD_nextInputType_e = 0;
pub type ZSTD_dictContentType_e = core::ffi::c_uint;
pub const ZSTD_dct_fullDict: ZSTD_dictContentType_e = 2;
pub const ZSTD_dct_rawContent: ZSTD_dictContentType_e = 1;
pub const ZSTD_dct_auto: ZSTD_dictContentType_e = 0;
pub type ZSTD_dictLoadMethod_e = core::ffi::c_uint;
pub const ZSTD_dlm_byRef: ZSTD_dictLoadMethod_e = 1;
pub const ZSTD_dlm_byCopy: ZSTD_dictLoadMethod_e = 0;
pub const ZSTD_MAXWINDOWSIZE_DEFAULT: u32 = (1u32 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).wrapping_add(1);
pub const ZSTD_NO_FORWARD_PROGRESS_MAX: core::ffi::c_int = 16;
pub const ZSTD_VERSION_MAJOR: core::ffi::c_int = 1;
pub const ZSTD_VERSION_MINOR: core::ffi::c_int = 5;
pub const ZSTD_VERSION_RELEASE: core::ffi::c_int = 8;
pub const ZSTD_VERSION_NUMBER: core::ffi::c_int =
    ZSTD_VERSION_MAJOR * 100 * 100 + ZSTD_VERSION_MINOR * 100 + ZSTD_VERSION_RELEASE;
pub const ZSTD_MAGICNUMBER: core::ffi::c_uint = 0xfd2fb528;
pub const ZSTD_MAGIC_DICTIONARY: core::ffi::c_uint = 0xec30a437;
pub const ZSTD_MAGIC_SKIPPABLE_START: core::ffi::c_int = 0x184d2a50;
pub const ZSTD_MAGIC_SKIPPABLE_MASK: core::ffi::c_uint = 0xfffffff0;
pub const ZSTD_BLOCKSIZELOG_MAX: core::ffi::c_int = 17;
pub const ZSTD_BLOCKSIZE_MAX: core::ffi::c_int = (1) << ZSTD_BLOCKSIZELOG_MAX;
pub const ZSTD_CONTENTSIZE_UNKNOWN: core::ffi::c_ulonglong =
    (0 as core::ffi::c_ulonglong).wrapping_sub(1);
pub const ZSTD_CONTENTSIZE_ERROR: core::ffi::c_ulonglong =
    (0 as core::ffi::c_ulonglong).wrapping_sub(2);
pub const ZSTD_SKIPPABLEHEADERSIZE: core::ffi::c_int = 8;
pub const ZSTD_WINDOWLOG_MAX_32: core::ffi::c_int = 30;
pub const ZSTD_WINDOWLOG_MAX_64: core::ffi::c_int = 31;
pub const ZSTD_BLOCKSIZE_MAX_MIN: core::ffi::c_int = (1) << 10;
pub const ZSTD_WINDOWLOG_LIMIT_DEFAULT: core::ffi::c_int = 27;
pub const ZSTD_d_format: core::ffi::c_int = 1000;
pub const ZSTD_d_stableOutBuffer: core::ffi::c_int = 1001;
pub const ZSTD_d_forceIgnoreChecksum: core::ffi::c_int = 1002;
pub const ZSTD_d_refMultipleDDicts: core::ffi::c_int = 1003;
pub const ZSTD_d_disableHuffmanAssembly: core::ffi::c_int = 1004;
pub const ZSTD_d_maxBlockSize: core::ffi::c_int = 1005;
pub const ZSTD_WINDOWLOG_ABSOLUTEMIN: core::ffi::c_int = 10;

#[inline]
unsafe fn ZSTD_customMalloc(size: size_t, customMem: ZSTD_customMem) -> *mut core::ffi::c_void {
    if (customMem.customAlloc).is_some() {
        return (customMem.customAlloc).unwrap_unchecked()(customMem.opaque, size);
    }
    malloc(size)
}
#[inline]
unsafe fn ZSTD_customCalloc(size: size_t, customMem: ZSTD_customMem) -> *mut core::ffi::c_void {
    if (customMem.customAlloc).is_some() {
        let ptr = (customMem.customAlloc).unwrap_unchecked()(customMem.opaque, size);
        ptr::write_bytes(ptr, 0, size);
        return ptr;
    }
    calloc(1, size)
}
#[inline]
unsafe fn ZSTD_customFree(ptr: *mut core::ffi::c_void, customMem: ZSTD_customMem) {
    if !ptr.is_null() {
        if (customMem.customFree).is_some() {
            (customMem.customFree).unwrap_unchecked()(customMem.opaque, ptr);
        } else {
            free(ptr);
        }
    }
}

const ZSTDv01_magicNumberLE: u32 = 0x1EB52FFD;

const ZSTDv02_MAGICNUMBER: core::ffi::c_uint = 0xFD2FB522;
const ZSTDv03_MAGICNUMBER: core::ffi::c_uint = 0xFD2FB523;
const ZSTDv04_MAGICNUMBER: core::ffi::c_uint = 0xFD2FB524;
const ZSTDv05_MAGICNUMBER: core::ffi::c_uint = 0xFD2FB525;
const ZSTDv06_MAGICNUMBER: core::ffi::c_uint = 0xFD2FB526;
const ZSTDv07_MAGICNUMBER: core::ffi::c_uint = 0xFD2FB527;

#[inline]
unsafe fn ZSTD_isLegacy(src: *const core::ffi::c_void, srcSize: size_t) -> u32 {
    is_legacy(unsafe { core::slice::from_raw_parts(src.cast::<u8>(), srcSize) })
}

fn is_legacy(src: &[u8]) -> u32 {
    let Some(chunk) = src.first_chunk() else {
        return 0;
    };

    match u32::from_le_bytes(*chunk) {
        ZSTDv01_magicNumberLE => 1,
        ZSTDv02_MAGICNUMBER => 2,
        ZSTDv03_MAGICNUMBER => 3,
        ZSTDv04_MAGICNUMBER => 4,
        ZSTDv05_MAGICNUMBER => 5,
        ZSTDv06_MAGICNUMBER => 6,
        ZSTDv07_MAGICNUMBER => 7,
        _ => 0,
    }
}

#[inline]
fn get_decompressed_size_legacy(src: &[u8]) -> Option<u64> {
    let ptr = src.as_ptr().cast();

    match is_legacy(src) {
        5 => {
            let mut fParams = ZSTDv05_parameters {
                srcSize: 0,
                windowLog: 0,
                contentLog: 0,
                hashLog: 0,
                searchLog: 0,
                searchLength: 0,
                targetLength: 0,
                strategy: ZSTDv05_fast,
            };

            match unsafe { ZSTDv05_getFrameParams(&mut fParams, ptr, src.len() as _) } {
                0 => Some(fParams.srcSize as core::ffi::c_ulonglong),
                _ => None,
            }
        }
        6 => {
            let mut fParams_0 = ZSTDv06_frameParams_s {
                frameContentSize: 0,
                windowLog: 0,
            };

            match unsafe { ZSTDv06_getFrameParams(&mut fParams_0, ptr, src.len() as _) } {
                0 => Some(fParams_0.frameContentSize),
                _ => None,
            }
        }
        7 => {
            let mut fParams_1 = ZSTDv07_frameParams {
                frameContentSize: 0,
                windowSize: 0,
                dictID: 0,
                checksumFlag: 0,
            };

            match unsafe { ZSTDv07_getFrameParams(&mut fParams_1, ptr, src.len() as _) } {
                0 => Some(fParams_1.frameContentSize),
                _ => None,
            }
        }

        _ => None,
    }
}
#[inline]
unsafe fn ZSTD_decompressLegacy(
    mut dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    mut src: *const core::ffi::c_void,
    compressedSize: size_t,
    mut dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    let version = ZSTD_isLegacy(src, compressedSize);
    let mut x: core::ffi::c_char = 0;
    if dst.is_null() {
        dst = &mut x as *mut core::ffi::c_char as *mut core::ffi::c_void;
    }
    if src.is_null() {
        src = &mut x as *mut core::ffi::c_char as *const core::ffi::c_void;
    }
    if dict.is_null() {
        dict = &mut x as *mut core::ffi::c_char as *const core::ffi::c_void;
    }
    match version {
        5 => {
            let mut result: size_t = 0;
            let zd = ZSTDv05_createDCtx();
            if zd.is_null() {
                return Error::memory_allocation.to_error_code();
            }
            result = ZSTDv05_decompress_usingDict(
                &mut *zd,
                dst,
                dstCapacity,
                src,
                compressedSize,
                dict,
                dictSize,
            );
            ZSTDv05_freeDCtx(zd);
            result
        }
        6 => {
            let mut result_0: size_t = 0;
            let zd_0 = ZSTDv06_createDCtx();
            if zd_0.is_null() {
                return Error::memory_allocation.to_error_code();
            }
            result_0 = ZSTDv06_decompress_usingDict(
                zd_0,
                dst,
                dstCapacity,
                src,
                compressedSize,
                dict,
                dictSize,
            );
            ZSTDv06_freeDCtx(zd_0);
            result_0
        }
        7 => {
            let mut result_1: size_t = 0;
            let zd_1 = ZSTDv07_createDCtx();
            if zd_1.is_null() {
                return Error::memory_allocation.to_error_code();
            }
            result_1 = ZSTDv07_decompress_usingDict(
                zd_1,
                dst,
                dstCapacity,
                src,
                compressedSize,
                dict,
                dictSize,
            );
            ZSTDv07_freeDCtx(zd_1);
            result_1
        }
        _ => Error::prefix_unknown.to_error_code(),
    }
}

#[inline]
unsafe fn ZSTD_findFrameSizeInfoLegacy(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> ZSTD_frameSizeInfo {
    find_frame_size_info_legacy(if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    })
}

unsafe fn find_frame_size_info_legacy(src: &[u8]) -> ZSTD_frameSizeInfo {
    let mut frameSizeInfo = ZSTD_frameSizeInfo {
        nbBlocks: 0,
        compressedSize: 0,
        decompressedBound: 0,
    };

    match is_legacy(src) {
        5 => {
            ZSTDv05_findFrameSizeInfoLegacy(
                src.as_ptr().cast(),
                src.len(),
                &mut frameSizeInfo.compressedSize,
                &mut frameSizeInfo.decompressedBound,
            );
        }
        6 => {
            ZSTDv06_findFrameSizeInfoLegacy(
                src.as_ptr().cast(),
                src.len(),
                &mut frameSizeInfo.compressedSize,
                &mut frameSizeInfo.decompressedBound,
            );
        }
        7 => {
            ZSTDv07_findFrameSizeInfoLegacy(
                src.as_ptr().cast(),
                src.len(),
                &mut frameSizeInfo.compressedSize,
                &mut frameSizeInfo.decompressedBound,
            );
        }
        _ => {
            frameSizeInfo.compressedSize = Error::prefix_unknown.to_error_code();
            frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
        }
    }

    if !ERR_isError(frameSizeInfo.compressedSize) && frameSizeInfo.compressedSize > src.len() {
        frameSizeInfo.compressedSize = Error::srcSize_wrong.to_error_code();
        frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
    }

    if frameSizeInfo.decompressedBound != ZSTD_CONTENTSIZE_ERROR {
        frameSizeInfo.nbBlocks = (frameSizeInfo.decompressedBound)
            .wrapping_div(ZSTD_BLOCKSIZE_MAX as core::ffi::c_ulonglong)
            as size_t;
    }

    frameSizeInfo
}

#[inline]
unsafe fn ZSTD_findFrameCompressedSizeLegacy(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    let frameSizeInfo = ZSTD_findFrameSizeInfoLegacy(src, srcSize);
    frameSizeInfo.compressedSize
}

#[inline]
unsafe fn ZSTD_freeLegacyStreamContext(
    legacyContext: *mut core::ffi::c_void,
    version: u32,
) -> size_t {
    match version {
        5 => ZBUFFv05_freeDCtx(legacyContext as *mut ZBUFFv05_DCtx),
        6 => ZBUFFv06_freeDCtx(legacyContext as *mut ZBUFFv06_DCtx),
        7 => ZBUFFv07_freeDCtx(legacyContext as *mut ZBUFFv07_DCtx),
        1 | 2 | 3 | _ => Error::version_unsupported.to_error_code(),
    }
}
#[inline]
unsafe fn ZSTD_initLegacyStream(
    legacyContext: *mut *mut core::ffi::c_void,
    prevVersion: u32,
    newVersion: u32,
    mut dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    let mut x: core::ffi::c_char = 0;
    if dict.is_null() {
        dict = &mut x as *mut core::ffi::c_char as *const core::ffi::c_void;
    }
    if prevVersion != newVersion {
        ZSTD_freeLegacyStreamContext(*legacyContext, prevVersion);
    }
    match newVersion {
        5 => {
            let dctx = if prevVersion != newVersion {
                ZBUFFv05_createDCtx()
            } else {
                *legacyContext as *mut ZBUFFv05_DCtx
            };
            if dctx.is_null() {
                return Error::memory_allocation.to_error_code();
            }
            ZBUFFv05_decompressInitDictionary(dctx, dict, dictSize);
            *legacyContext = dctx as *mut core::ffi::c_void;
            0
        }
        6 => {
            let dctx_0 = if prevVersion != newVersion {
                ZBUFFv06_createDCtx()
            } else {
                *legacyContext as *mut ZBUFFv06_DCtx
            };
            if dctx_0.is_null() {
                return Error::memory_allocation.to_error_code();
            }
            ZBUFFv06_decompressInitDictionary(dctx_0, dict, dictSize);
            *legacyContext = dctx_0 as *mut core::ffi::c_void;
            0
        }
        7 => {
            let dctx_1 = if prevVersion != newVersion {
                ZBUFFv07_createDCtx()
            } else {
                *legacyContext as *mut ZBUFFv07_DCtx
            };
            if dctx_1.is_null() {
                return Error::memory_allocation.to_error_code();
            }
            ZBUFFv07_decompressInitDictionary(dctx_1, dict, dictSize);
            *legacyContext = dctx_1 as *mut core::ffi::c_void;
            0
        }
        1 | 2 | 3 | _ => 0,
    }
}

#[inline]
unsafe fn ZSTD_decompressLegacyStream(
    legacyContext: *mut core::ffi::c_void,
    version: u32,
    output: &mut ZSTD_outBuffer,
    input: &mut ZSTD_inBuffer,
) -> size_t {
    static mut x: core::ffi::c_char = 0;
    if (output.dst).is_null() {
        output.dst = &raw mut x as *mut core::ffi::c_void;
    }
    if (input.src).is_null() {
        input.src = &raw mut x as *const core::ffi::c_void;
    }
    match version {
        5 => {
            let dctx = legacyContext as *mut ZBUFFv05_DCtx;
            let src =
                (input.src as *const core::ffi::c_char).add(input.pos) as *const core::ffi::c_void;
            let mut readSize = (input.size).wrapping_sub(input.pos);
            let dst =
                (output.dst as *mut core::ffi::c_char).add(output.pos) as *mut core::ffi::c_void;
            let mut decodedSize = (output.size).wrapping_sub(output.pos);
            let hintSize =
                ZBUFFv05_decompressContinue(&mut *dctx, dst, &mut decodedSize, src, &mut readSize);
            output.pos = (output.pos).wrapping_add(decodedSize);
            input.pos = (input.pos).wrapping_add(readSize);
            hintSize
        }
        6 => {
            let dctx_0 = legacyContext as *mut ZBUFFv06_DCtx;
            let src_0 =
                (input.src as *const core::ffi::c_char).add(input.pos) as *const core::ffi::c_void;
            let mut readSize_0 = (input.size).wrapping_sub(input.pos);
            let dst_0 =
                (output.dst as *mut core::ffi::c_char).add(output.pos) as *mut core::ffi::c_void;
            let mut decodedSize_0 = (output.size).wrapping_sub(output.pos);
            let hintSize_0 = ZBUFFv06_decompressContinue(
                dctx_0,
                dst_0,
                &mut decodedSize_0,
                src_0,
                &mut readSize_0,
            );
            output.pos = (output.pos).wrapping_add(decodedSize_0);
            input.pos = (input.pos).wrapping_add(readSize_0);
            hintSize_0
        }
        7 => {
            let dctx_1 = legacyContext as *mut ZBUFFv07_DCtx;
            let src_1 =
                (input.src as *const core::ffi::c_char).add(input.pos) as *const core::ffi::c_void;
            let mut readSize_1 = (input.size).wrapping_sub(input.pos);
            let dst_1 =
                (output.dst as *mut core::ffi::c_char).add(output.pos) as *mut core::ffi::c_void;
            let mut decodedSize_1 = (output.size).wrapping_sub(output.pos);
            let hintSize_1 = ZBUFFv07_decompressContinue(
                dctx_1,
                dst_1,
                &mut decodedSize_1,
                src_1,
                &mut readSize_1,
            );
            output.pos = (output.pos).wrapping_add(decodedSize_1);
            input.pos = (input.pos).wrapping_add(readSize_1);
            hintSize_1
        }
        1 | 2 | 3 | _ => Error::version_unsupported.to_error_code(),
    }
}

pub const DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT: core::ffi::c_int = 4;
pub const DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT: core::ffi::c_int = 3;
pub const DDICT_HASHSET_TABLE_BASE_SIZE: core::ffi::c_int = 64;
pub const DDICT_HASHSET_RESIZE_FACTOR: core::ffi::c_int = 2;

fn ZSTD_DDictHashSet_getIndex(hashSet: &ZSTD_DDictHashSet, dictID: u32) -> size_t {
    let hash = ZSTD_XXH64_slice(&dictID.to_ne_bytes(), 0);
    hash as size_t & (hashSet.ddictPtrTableSize).wrapping_sub(1)
}

unsafe fn ZSTD_DDictHashSet_emplaceDDict(
    hashSet: &mut ZSTD_DDictHashSet,
    ddict: *const ZSTD_DDict,
) -> size_t {
    let dictID = ZSTD_getDictID_fromDDict(ddict);
    let mut idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID);
    let idxRangeMask = (hashSet.ddictPtrTableSize).wrapping_sub(1);
    if hashSet.ddictPtrCount == hashSet.ddictPtrTableSize {
        return Error::GENERIC.to_error_code();
    }
    while !(*(hashSet.ddictPtrTable).add(idx)).is_null() {
        if ZSTD_getDictID_fromDDict(*(hashSet.ddictPtrTable).add(idx)) == dictID {
            let fresh0 = &mut (*(hashSet.ddictPtrTable).add(idx));
            *fresh0 = ddict;
            return 0;
        }
        idx &= idxRangeMask;
        idx = idx.wrapping_add(1);
    }
    let fresh1 = &mut (*(hashSet.ddictPtrTable).add(idx));
    *fresh1 = ddict;
    hashSet.ddictPtrCount = (hashSet.ddictPtrCount).wrapping_add(1);
    hashSet.ddictPtrCount;
    0
}

unsafe fn ZSTD_DDictHashSet_expand(
    hashSet: &mut ZSTD_DDictHashSet,
    customMem: ZSTD_customMem,
) -> size_t {
    let newTableSize = hashSet.ddictPtrTableSize * DDICT_HASHSET_RESIZE_FACTOR as size_t;
    let newTable = ZSTD_customCalloc(
        (::core::mem::size_of::<*mut ZSTD_DDict>()).wrapping_mul(newTableSize),
        customMem,
    ) as *mut *const ZSTD_DDict;
    let oldTable = hashSet.ddictPtrTable;
    let oldTableSize = hashSet.ddictPtrTableSize;
    let mut i: size_t = 0;
    if newTable.is_null() {
        return Error::memory_allocation.to_error_code();
    }
    hashSet.ddictPtrTable = newTable;
    hashSet.ddictPtrTableSize = newTableSize;
    hashSet.ddictPtrCount = 0;
    i = 0;
    while i < oldTableSize {
        if !(*oldTable.add(i)).is_null() {
            let err_code = ZSTD_DDictHashSet_emplaceDDict(hashSet, *oldTable.add(i));
            if ERR_isError(err_code) {
                return err_code;
            }
        }
        i = i.wrapping_add(1);
    }
    ZSTD_customFree(oldTable as *mut core::ffi::c_void, customMem);
    0
}

unsafe fn ZSTD_DDictHashSet_getDDict(
    hashSet: &mut ZSTD_DDictHashSet,
    dictID: u32,
) -> *const ZSTD_DDict {
    let mut idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID);
    let idxRangeMask = (hashSet.ddictPtrTableSize).wrapping_sub(1);
    loop {
        let currDictID = ZSTD_getDictID_fromDDict(*(hashSet.ddictPtrTable).add(idx)) as size_t;
        if currDictID == dictID as size_t || currDictID == 0 {
            break;
        }
        idx &= idxRangeMask;
        idx = idx.wrapping_add(1);
    }
    *(hashSet.ddictPtrTable).add(idx)
}

unsafe fn ZSTD_createDDictHashSet(customMem: ZSTD_customMem) -> *mut ZSTD_DDictHashSet {
    let ret = ZSTD_customMalloc(::core::mem::size_of::<ZSTD_DDictHashSet>(), customMem)
        as *mut ZSTD_DDictHashSet;
    if ret.is_null() {
        return core::ptr::null_mut();
    }
    (*ret).ddictPtrTable = ZSTD_customCalloc(
        (DDICT_HASHSET_TABLE_BASE_SIZE as size_t)
            .wrapping_mul(::core::mem::size_of::<*mut ZSTD_DDict>()),
        customMem,
    ) as *mut *const ZSTD_DDict;
    if ((*ret).ddictPtrTable).is_null() {
        ZSTD_customFree(ret as *mut core::ffi::c_void, customMem);
        return core::ptr::null_mut();
    }
    (*ret).ddictPtrTableSize = DDICT_HASHSET_TABLE_BASE_SIZE as size_t;
    (*ret).ddictPtrCount = 0;
    ret
}

unsafe fn ZSTD_freeDDictHashSet(hashSet: *mut ZSTD_DDictHashSet, customMem: ZSTD_customMem) {
    if !hashSet.is_null() && !((*hashSet).ddictPtrTable).is_null() {
        ZSTD_customFree(
            (*hashSet).ddictPtrTable as *mut core::ffi::c_void,
            customMem,
        );
    }
    if !hashSet.is_null() {
        ZSTD_customFree(hashSet as *mut core::ffi::c_void, customMem);
    }
}
unsafe fn ZSTD_DDictHashSet_addDDict(
    hashSet: &mut ZSTD_DDictHashSet,
    ddict: *const ZSTD_DDict,
    customMem: ZSTD_customMem,
) -> size_t {
    if hashSet.ddictPtrCount * DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT as size_t
        / hashSet.ddictPtrTableSize
        * DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT as size_t
        != 0
    {
        let err_code = ZSTD_DDictHashSet_expand(hashSet, customMem);
        if ERR_isError(err_code) {
            return err_code;
        }
    }
    let err_code_0 = ZSTD_DDictHashSet_emplaceDDict(hashSet, ddict);
    if ERR_isError(err_code_0) {
        return err_code_0;
    }
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_sizeof_DCtx))]
pub unsafe extern "C" fn ZSTD_sizeof_DCtx(dctx: *const ZSTD_DCtx) -> size_t {
    if dctx.is_null() {
        return 0;
    }
    (::core::mem::size_of::<ZSTD_DCtx>())
        .wrapping_add(ZSTD_sizeof_DDict((*dctx).ddictLocal))
        .wrapping_add((*dctx).inBuffSize)
        .wrapping_add((*dctx).outBuffSize)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateDCtxSize))]
pub unsafe extern "C" fn ZSTD_estimateDCtxSize() -> size_t {
    ::core::mem::size_of::<ZSTD_DCtx>()
}

const fn ZSTD_startingInputLength(format: Format) -> size_t {
    match format {
        Format::ZSTD_f_zstd1 => 5,
        Format::ZSTD_f_zstd1_magicless => 1,
    }
}

unsafe fn ZSTD_DCtx_resetParameters(dctx: *mut ZSTD_DCtx) {
    (*dctx).format = Format::ZSTD_f_zstd1;
    (*dctx).maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT as size_t;
    (*dctx).outBufferMode = BufferMode::Buffered;
    (*dctx).forceIgnoreChecksum = ZSTD_d_validateChecksum;
    (*dctx).refMultipleDDicts = MultipleDDicts::Single;
    (*dctx).disableHufAsm = 0;
    (*dctx).maxBlockSizeParam = 0;
}

unsafe fn ZSTD_initDCtx_internal(dctx: *mut ZSTD_DCtx) {
    (*dctx).staticSize = 0;
    (*dctx).ddict = core::ptr::null();
    (*dctx).ddictLocal = core::ptr::null_mut();
    (*dctx).dictEnd = core::ptr::null();
    (*dctx).ddictIsCold = 0;
    (*dctx).dictUses = ZSTD_dont_use;
    (*dctx).inBuff = core::ptr::null_mut();
    (*dctx).inBuffSize = 0;
    (*dctx).outBuffSize = 0;
    (*dctx).streamStage = StreamStage::Init;
    (*dctx).legacyContext = core::ptr::null_mut();
    (*dctx).previousLegacyVersion = 0;
    (*dctx).noForwardProgress = 0;
    (*dctx).oversizedDuration = 0;
    (*dctx).isFrameDecompression = 1;
    (*dctx).bmi2 = ZSTD_cpuSupportsBmi2() as _;
    (*dctx).ddictSet = core::ptr::null_mut();
    ZSTD_DCtx_resetParameters(dctx);
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initStaticDCtx))]
pub unsafe extern "C" fn ZSTD_initStaticDCtx(
    workspace: *mut core::ffi::c_void,
    workspaceSize: size_t,
) -> *mut ZSTD_DCtx {
    let dctx = workspace as *mut ZSTD_DCtx;
    if workspace as size_t & 7 != 0 {
        return core::ptr::null_mut();
    }
    if workspaceSize < ::core::mem::size_of::<ZSTD_DCtx>() {
        return core::ptr::null_mut();
    }
    ZSTD_initDCtx_internal(dctx);
    (*dctx).staticSize = workspaceSize;
    (*dctx).inBuff = dctx.offset(1) as *mut core::ffi::c_char;
    dctx
}

unsafe fn ZSTD_createDCtx_internal(customMem: ZSTD_customMem) -> *mut ZSTD_DCtx {
    if (customMem.customAlloc).is_none() ^ (customMem.customFree).is_none() {
        return core::ptr::null_mut();
    }

    let dctx = ZSTD_customMalloc(::core::mem::size_of::<ZSTD_DCtx>(), customMem) as *mut ZSTD_DCtx;
    if dctx.is_null() {
        return core::ptr::null_mut();
    }

    (*dctx).customMem = customMem;
    ZSTD_initDCtx_internal(dctx);
    dctx
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createDCtx_advanced))]
pub unsafe extern "C" fn ZSTD_createDCtx_advanced(customMem: ZSTD_customMem) -> *mut ZSTD_DCtx {
    ZSTD_createDCtx_internal(customMem)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createDCtx))]
pub unsafe extern "C" fn ZSTD_createDCtx() -> *mut ZSTD_DCtx {
    ZSTD_createDCtx_internal(ZSTD_defaultCMem)
}
unsafe fn ZSTD_clearDict(dctx: *mut ZSTD_DCtx) {
    ZSTD_freeDDict((*dctx).ddictLocal);
    (*dctx).ddictLocal = core::ptr::null_mut();
    (*dctx).ddict = core::ptr::null();
    (*dctx).dictUses = ZSTD_dont_use;
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_freeDCtx))]
pub unsafe extern "C" fn ZSTD_freeDCtx(dctx: *mut ZSTD_DCtx) -> size_t {
    if dctx.is_null() {
        return 0;
    }
    if (*dctx).staticSize != 0 {
        return Error::memory_allocation.to_error_code();
    }
    let cMem = (*dctx).customMem;
    ZSTD_clearDict(dctx);
    ZSTD_customFree((*dctx).inBuff as *mut core::ffi::c_void, cMem);
    (*dctx).inBuff = core::ptr::null_mut();
    if !((*dctx).legacyContext).is_null() {
        ZSTD_freeLegacyStreamContext((*dctx).legacyContext, (*dctx).previousLegacyVersion);
    }
    if !((*dctx).ddictSet).is_null() {
        ZSTD_freeDDictHashSet((*dctx).ddictSet, cMem);
        (*dctx).ddictSet = core::ptr::null_mut();
    }
    ZSTD_customFree(dctx as *mut core::ffi::c_void, cMem);
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_copyDCtx))]
pub unsafe extern "C" fn ZSTD_copyDCtx(dstDCtx: *mut ZSTD_DCtx, srcDCtx: *const ZSTD_DCtx) {
    let toCopy = (&mut (*dstDCtx).inBuff as *mut *mut core::ffi::c_char as *mut core::ffi::c_char)
        .offset_from(dstDCtx as *mut core::ffi::c_char) as core::ffi::c_long
        as size_t;
    libc::memcpy(
        dstDCtx as *mut core::ffi::c_void,
        srcDCtx as *const core::ffi::c_void,
        toCopy as libc::size_t,
    );
}
unsafe fn ZSTD_DCtx_selectFrameDDict(dctx: *mut ZSTD_DCtx) {
    if !((*dctx).ddict).is_null() {
        let frameDDict =
            ZSTD_DDictHashSet_getDDict((*dctx).ddictSet.as_mut().unwrap(), (*dctx).fParams.dictID);
        if !frameDDict.is_null() {
            ZSTD_clearDict(dctx);
            (*dctx).dictID = (*dctx).fParams.dictID;
            (*dctx).ddict = frameDDict;
            (*dctx).dictUses = ZSTD_use_indefinitely;
        }
    }
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_isFrame))]
pub unsafe extern "C" fn ZSTD_isFrame(
    buffer: *const core::ffi::c_void,
    size: size_t,
) -> core::ffi::c_uint {
    let src = if buffer.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(buffer.cast(), size)
    };

    is_frame(src) as core::ffi::c_uint
}

fn is_frame(src: &[u8]) -> bool {
    let [a, b, c, d] = *src else {
        return false;
    };

    let magic = u32::from_le_bytes([a, b, c, d]);
    if magic == ZSTD_MAGICNUMBER {
        return true;
    }

    if magic & ZSTD_MAGIC_SKIPPABLE_MASK == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint {
        return true;
    }

    if is_legacy(src) != 0 {
        return true;
    }

    false
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_isSkippableFrame))]
pub unsafe extern "C" fn ZSTD_isSkippableFrame(
    buffer: *const core::ffi::c_void,
    size: size_t,
) -> core::ffi::c_uint {
    let src = if buffer.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(buffer.cast(), size)
    };

    is_skippable_frame(src) as core::ffi::c_uint
}

fn is_skippable_frame(src: &[u8]) -> bool {
    let [a, b, c, d] = *src else {
        return false;
    };

    let magic = u32::from_le_bytes([a, b, c, d]);
    if magic & ZSTD_MAGIC_SKIPPABLE_MASK == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint {
        return true;
    }

    false
}

fn frame_header_size_internal(src: &[u8], format: Format) -> usize {
    static ZSTD_fcs_fieldSize: [u8; 4] = [0, 2, 4, 8];
    static ZSTD_did_fieldSize: [u8; 4] = [0, 1, 2, 4];

    let minInputSize = ZSTD_startingInputLength(format);
    let Some([.., fhd]) = src.get(..minInputSize as usize) else {
        return Error::srcSize_wrong.to_error_code();
    };

    let dictID = fhd & 0b11;
    let singleSegment = (fhd >> 5 & 1) != 0;
    let fcsId = fhd >> 6;

    minInputSize
        + usize::from(!singleSegment)
        + usize::from(ZSTD_did_fieldSize[usize::from(dictID)])
        + usize::from(ZSTD_fcs_fieldSize[usize::from(fcsId)])
        + usize::from(singleSegment && fcsId == 0)
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_frameHeaderSize))]
pub unsafe extern "C" fn ZSTD_frameHeaderSize(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    let src = if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    };

    frame_header_size_internal(src, Format::ZSTD_f_zstd1)
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getFrameHeader))]
pub unsafe extern "C" fn ZSTD_getFrameHeader(
    zfhPtr: *mut ZSTD_FrameHeader,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, Format::ZSTD_f_zstd1 as _)
}

fn get_frame_header(zfhPtr: &mut ZSTD_FrameHeader, src: &[u8]) -> size_t {
    get_frame_header_advanced(zfhPtr, src, Format::ZSTD_f_zstd1)
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getFrameHeader_advanced))]
pub unsafe extern "C" fn ZSTD_getFrameHeader_advanced(
    zfhPtr: *mut ZSTD_FrameHeader,
    src: *const core::ffi::c_void,
    srcSize: size_t,
    format: ZSTD_format_e,
) -> size_t {
    // Apparently some sanitizers require this?
    unsafe { zfhPtr.write(ZSTD_FrameHeader::default()) };

    let Some(zfhPtr) = zfhPtr.as_mut() else {
        return Error::GENERIC.to_error_code();
    };

    // Compatibility: this is stricter than zstd.
    let Ok(format) = Format::try_from(format) else {
        return Error::GENERIC.to_error_code();
    };

    if srcSize > 0 && src.is_null() {
        return Error::GENERIC.to_error_code();
    }

    get_frame_header_advanced(
        zfhPtr,
        if src.is_null() {
            &[]
        } else {
            core::slice::from_raw_parts(src as *const u8, srcSize)
        },
        format,
    )
}

fn get_frame_header_advanced(zfhPtr: &mut ZSTD_FrameHeader, src: &[u8], format: Format) -> size_t {
    let minInputSize = ZSTD_startingInputLength(format);
    if src.len() < minInputSize as usize {
        if !src.is_empty()
            && format != Format::ZSTD_f_zstd1_magicless
            && src != &ZSTD_MAGICNUMBER.to_le_bytes()[..src.len()]
        {
            let mut hbuf = ZSTD_MAGIC_SKIPPABLE_START.to_le_bytes();
            hbuf[..src.len()].copy_from_slice(src);
            if u32::from_le_bytes(hbuf) & ZSTD_MAGIC_SKIPPABLE_MASK
                != ZSTD_MAGIC_SKIPPABLE_START as u32
            {
                return Error::prefix_unknown.to_error_code();
            }
        }
        return minInputSize;
    }

    let first_word = u32::from_le_bytes(*src.first_chunk().unwrap());

    if format != Format::ZSTD_f_zstd1_magicless && first_word != ZSTD_MAGICNUMBER {
        if first_word & ZSTD_MAGIC_SKIPPABLE_MASK == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint
        {
            if src.len() < ZSTD_SKIPPABLEHEADERSIZE as usize {
                return ZSTD_SKIPPABLEHEADERSIZE as size_t;
            }

            let dictID = first_word.wrapping_sub(ZSTD_MAGIC_SKIPPABLE_START as u32);
            let frameContentSize =
                u32::from_le_bytes(*src[ZSTD_FRAMEIDSIZE..].first_chunk().unwrap());

            *zfhPtr = ZSTD_FrameHeader {
                frameContentSize: u64::from(frameContentSize),
                windowSize: 0,
                blockSizeMax: 0,
                frameType: ZSTD_skippableFrame,
                headerSize: ZSTD_SKIPPABLEHEADERSIZE as core::ffi::c_uint,
                dictID,
                checksumFlag: 0,
                _reserved1: 0,
                _reserved2: 0,
            };

            return 0;
        }
        return Error::prefix_unknown.to_error_code();
    }

    let fhsize = frame_header_size_internal(src, format);
    if src.len() < fhsize {
        return fhsize;
    }

    let fhdByte = src[minInputSize as usize - 1];
    let dictIDSizeCode = fhdByte & 0b11;
    let checksumFlag = u32::from(fhdByte) >> 2 & 1;
    let singleSegment = (u32::from(fhdByte) >> 5 & 1) != 0;
    let fcsID = (u32::from(fhdByte) >> 6) as u32;

    let mut windowSize = 0;

    if fhdByte & 0x8 != 0 {
        return Error::frameParameter_unsupported.to_error_code();
    }

    let mut pos = minInputSize as usize;
    if !singleSegment {
        let wlByte = src[pos];
        pos += 1;
        let windowLog = ((i32::from(wlByte) / 8) + ZSTD_WINDOWLOG_ABSOLUTEMIN) as u32;

        if windowLog > (if size_of::<usize>() == 4 { 30 } else { 31 }) as u32 {
            return Error::frameParameter_windowTooLarge.to_error_code();
        }

        windowSize = 1u64 << windowLog;
        windowSize = windowSize.wrapping_add((windowSize / 8) * (wlByte & 7) as u64);
    }

    let dictID;
    match dictIDSizeCode {
        1 => {
            dictID = u32::from(src[pos]);
            pos += 1;
        }
        2 => {
            dictID = u32::from(u16::from_le_bytes(src[pos..][..2].try_into().unwrap()));
            pos += 2;
        }
        3 => {
            dictID = u32::from_le_bytes(src[pos..][..4].try_into().unwrap());
            pos += 4;
        }
        _ => {
            dictID = 0;
        }
    }

    let frameContentSize = match fcsID {
        1 => u64::from(u16::from_le_bytes(src[pos..][..2].try_into().unwrap())) + 256,
        2 => u64::from(u32::from_le_bytes(src[pos..][..4].try_into().unwrap())),
        3 => u64::from_le_bytes(src[pos..][..8].try_into().unwrap()),
        _ if singleSegment => u64::from(src[pos]),
        _ => ZSTD_CONTENTSIZE_UNKNOWN,
    };

    if singleSegment {
        windowSize = frameContentSize;
    }

    *zfhPtr = ZSTD_FrameHeader {
        frameContentSize: frameContentSize as core::ffi::c_ulonglong,
        windowSize: windowSize as core::ffi::c_ulonglong,
        blockSizeMax: Ord::min(windowSize, 1 << 17) as u32,
        frameType: ZSTD_frame,
        headerSize: fhsize as u32,
        dictID,
        checksumFlag,
        _reserved1: 0,
        _reserved2: 0,
    };

    0
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getFrameContentSize))]
pub unsafe extern "C" fn ZSTD_getFrameContentSize(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> core::ffi::c_ulonglong {
    let src = if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    };

    get_frame_content_size(src)
}

fn get_frame_content_size(src: &[u8]) -> u64 {
    if is_legacy(src) != 0 {
        return match get_decompressed_size_legacy(src) {
            None | Some(0) => ZSTD_CONTENTSIZE_UNKNOWN,
            Some(decompressed_size) => decompressed_size,
        };
    }

    let mut zfh = ZSTD_FrameHeader::default();
    if get_frame_header_advanced(&mut zfh, src, Format::ZSTD_f_zstd1) != 0 {
        return ZSTD_CONTENTSIZE_ERROR;
    }

    if zfh.frameType == ZSTD_skippableFrame {
        0
    } else {
        zfh.frameContentSize
    }
}

unsafe fn readSkippableFrameSize(src: *const core::ffi::c_void, srcSize: size_t) -> size_t {
    read_skippable_frame_size(if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    })
}

fn read_skippable_frame_size(src: &[u8]) -> size_t {
    let skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE as usize;

    let [_, _, _, _, a, b, c, d, ..] = *src else {
        return Error::srcSize_wrong.to_error_code();
    };

    let size = u32::from_le_bytes([a, b, c, d]);

    if size.wrapping_add(8) < size {
        return Error::frameParameter_unsupported.to_error_code();
    }

    let skippableSize = skippableHeaderSize.wrapping_add(size as usize);
    if skippableSize > src.len() {
        return Error::srcSize_wrong.to_error_code();
    }

    skippableSize
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_readSkippableFrame))]
pub unsafe extern "C" fn ZSTD_readSkippableFrame(
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    magicVariant: *mut core::ffi::c_uint,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    if srcSize < 8 {
        return Error::srcSize_wrong.to_error_code();
    }
    let magicNumber = MEM_readLE32(src);
    let skippableFrameSize = readSkippableFrameSize(src, srcSize);
    let skippableContentSize = skippableFrameSize.wrapping_sub(ZSTD_SKIPPABLEHEADERSIZE as size_t);
    if ZSTD_isSkippableFrame(src, srcSize) == 0 {
        return Error::frameParameter_unsupported.to_error_code();
    }
    if skippableFrameSize < 8 || skippableFrameSize > srcSize {
        return Error::srcSize_wrong.to_error_code();
    }
    if skippableContentSize > dstCapacity {
        return Error::dstSize_tooSmall.to_error_code();
    }
    if skippableContentSize > 0 && !dst.is_null() {
        libc::memcpy(
            dst,
            (src as *const u8).offset(8) as *const core::ffi::c_void,
            skippableContentSize as libc::size_t,
        );
    }
    if !magicVariant.is_null() {
        *magicVariant = magicNumber.wrapping_sub(ZSTD_MAGIC_SKIPPABLE_START as u32);
    }
    skippableContentSize
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_findDecompressedSize))]
pub unsafe extern "C" fn ZSTD_findDecompressedSize(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> core::ffi::c_ulonglong {
    let src = if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    };

    find_decompressed_size(src)
}

fn find_decompressed_size(mut src: &[u8]) -> u64 {
    let mut totalDstSize = 0u64;

    while let [a, b, c, d, _, ..] = *src {
        let magicNumber = u32::from_le_bytes([a, b, c, d]);
        if magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK
            == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint
        {
            let skippableSize = read_skippable_frame_size(src);
            if ERR_isError(skippableSize) {
                return ZSTD_CONTENTSIZE_ERROR;
            }
            src = &src[skippableSize..];
        } else {
            let fcs = get_frame_content_size(src);
            if fcs >= ZSTD_CONTENTSIZE_ERROR {
                return fcs;
            }
            if totalDstSize.wrapping_add(fcs) < totalDstSize {
                return ZSTD_CONTENTSIZE_ERROR;
            }
            totalDstSize = totalDstSize.wrapping_add(fcs);
            let frameSrcSize = ZSTD_findFrameCompressedSize_advanced(src, Format::ZSTD_f_zstd1);
            if ERR_isError(frameSrcSize) {
                return ZSTD_CONTENTSIZE_ERROR;
            }
            src = &src[frameSrcSize..];
        }
    }

    if !src.is_empty() {
        return ZSTD_CONTENTSIZE_ERROR;
    }

    totalDstSize
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getDecompressedSize))]
pub unsafe extern "C" fn ZSTD_getDecompressedSize(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> core::ffi::c_ulonglong {
    let ret = ZSTD_getFrameContentSize(src, srcSize);
    if ret >= ZSTD_CONTENTSIZE_ERROR {
        0
    } else {
        ret
    }
}

unsafe fn ZSTD_decodeFrameHeader(dctx: *mut ZSTD_DCtx, src: &[u8]) -> size_t {
    let result = get_frame_header_advanced(&mut (*dctx).fParams, src, (*dctx).format);
    if ERR_isError(result) {
        return result;
    }
    if result > 0 {
        return Error::srcSize_wrong.to_error_code();
    }
    if (*dctx).refMultipleDDicts == MultipleDDicts::Multiple && !((*dctx).ddictSet).is_null() {
        ZSTD_DCtx_selectFrameDDict(dctx);
    }
    if (*dctx).fParams.dictID != 0 && (*dctx).dictID != (*dctx).fParams.dictID {
        return Error::dictionary_wrong.to_error_code();
    }
    (*dctx).validateChecksum =
        ((*dctx).fParams.checksumFlag != 0 && (*dctx).forceIgnoreChecksum as u64 == 0) as u32;
    if (*dctx).validateChecksum != 0 {
        ZSTD_XXH64_reset(&mut (*dctx).xxhState, 0);
    }
    (*dctx).processedCSize = ((*dctx).processedCSize as size_t).wrapping_add(src.len()) as u64;
    0
}

fn ZSTD_errorFrameSizeInfo(ret: size_t) -> ZSTD_frameSizeInfo {
    ZSTD_frameSizeInfo {
        nbBlocks: 0,
        compressedSize: ret,
        decompressedBound: ZSTD_CONTENTSIZE_ERROR,
    }
}

fn find_frame_size_info(src: &[u8], format: Format) -> ZSTD_frameSizeInfo {
    let mut frameSizeInfo = ZSTD_frameSizeInfo {
        nbBlocks: 0,
        compressedSize: 0,
        decompressedBound: 0,
    };

    if format == Format::ZSTD_f_zstd1 && is_legacy(src) != 0 {
        return unsafe { find_frame_size_info_legacy(src) };
    }

    if format == Format::ZSTD_f_zstd1
        && src.len() >= ZSTD_SKIPPABLEHEADERSIZE as usize
        && u32::from_le_bytes(*src.first_chunk().unwrap()) & ZSTD_MAGIC_SKIPPABLE_MASK
            == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint
    {
        frameSizeInfo.compressedSize = read_skippable_frame_size(src);
        frameSizeInfo
    } else {
        let mut ip = 0;
        let mut remainingSize = src.len();
        let mut nbBlocks = 0usize;
        let mut zfh = ZSTD_FrameHeader {
            frameContentSize: 0,
            windowSize: 0,
            blockSizeMax: 0,
            frameType: ZSTD_frame,
            headerSize: 0,
            dictID: 0,
            checksumFlag: 0,
            _reserved1: 0,
            _reserved2: 0,
        };
        let ret = get_frame_header_advanced(&mut zfh, src, format);
        if ERR_isError(ret) {
            return ZSTD_errorFrameSizeInfo(ret);
        }
        if ret > 0 {
            return ZSTD_errorFrameSizeInfo(Error::srcSize_wrong.to_error_code());
        }
        ip += zfh.headerSize as usize;
        remainingSize = remainingSize.wrapping_sub(zfh.headerSize as size_t);
        loop {
            let mut blockProperties = blockProperties_t {
                blockType: BlockType::Raw,
                lastBlock: 0,
                origSize: 0,
            };
            let cBlockSize = unsafe {
                ZSTD_getcBlockSize(
                    src[ip..].as_ptr().cast(),
                    remainingSize,
                    &mut blockProperties,
                )
            };
            if ERR_isError(cBlockSize) {
                return ZSTD_errorFrameSizeInfo(cBlockSize);
            }
            if ZSTD_blockHeaderSize.wrapping_add(cBlockSize) > remainingSize {
                return ZSTD_errorFrameSizeInfo(Error::srcSize_wrong.to_error_code());
            }
            ip += ZSTD_blockHeaderSize.wrapping_add(cBlockSize) as usize;
            remainingSize =
                remainingSize.wrapping_sub(ZSTD_blockHeaderSize.wrapping_add(cBlockSize));
            nbBlocks = nbBlocks.wrapping_add(1);
            if blockProperties.lastBlock != 0 {
                break;
            }
        }
        if zfh.checksumFlag != 0 {
            if remainingSize < 4 {
                return ZSTD_errorFrameSizeInfo(Error::srcSize_wrong.to_error_code());
            }
            ip += 4;
        }
        frameSizeInfo.nbBlocks = nbBlocks;
        frameSizeInfo.compressedSize = ip as size_t;
        frameSizeInfo.decompressedBound = if zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN {
            zfh.frameContentSize
        } else {
            (nbBlocks as core::ffi::c_ulonglong)
                .wrapping_mul(zfh.blockSizeMax as core::ffi::c_ulonglong)
        };
        frameSizeInfo
    }
}

fn ZSTD_findFrameCompressedSize_advanced(src: &[u8], format: Format) -> size_t {
    find_frame_size_info(src, format).compressedSize
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_findFrameCompressedSize))]
pub unsafe extern "C" fn ZSTD_findFrameCompressedSize(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    let src = if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    };

    ZSTD_findFrameCompressedSize_advanced(src, Format::ZSTD_f_zstd1)
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressBound))]
pub unsafe extern "C" fn ZSTD_decompressBound(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> core::ffi::c_ulonglong {
    decompress_bound(if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    })
}

fn decompress_bound(mut src: &[u8]) -> core::ffi::c_ulonglong {
    let mut bound = 0;

    while !src.is_empty() {
        let frameSizeInfo = find_frame_size_info(src, Format::ZSTD_f_zstd1);
        let compressedSize = frameSizeInfo.compressedSize;
        let decompressedBound = frameSizeInfo.decompressedBound;
        if ERR_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR {
            return ZSTD_CONTENTSIZE_ERROR;
        }
        src = &src[compressedSize as usize..];
        bound += decompressedBound;
    }

    bound
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressionMargin))]
pub unsafe extern "C" fn ZSTD_decompressionMargin(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    decompression_margin(if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast(), srcSize)
    })
}

fn decompression_margin(mut src: &[u8]) -> size_t {
    let mut margin = 0;
    let mut maxBlockSize = 0;

    /* Iterate over each frame */
    while !src.is_empty() {
        let frameSizeInfo = find_frame_size_info(src, Format::ZSTD_f_zstd1);
        let compressedSize = frameSizeInfo.compressedSize;
        let decompressedBound = frameSizeInfo.decompressedBound;

        let mut zfh = ZSTD_FrameHeader::default();
        let err_code = get_frame_header(&mut zfh, src);
        if ERR_isError(err_code) {
            return err_code;
        }

        if ERR_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR {
            return Error::corruption_detected.to_error_code();
        }

        if zfh.frameType as core::ffi::c_uint == ZSTD_frame as core::ffi::c_uint {
            /* Add the frame header to our margin */
            margin += zfh.headerSize as size_t;
            margin += if zfh.checksumFlag != 0 { 4 } else { 0 };
            margin += 3 * frameSizeInfo.nbBlocks;
            maxBlockSize = Ord::max(maxBlockSize, zfh.blockSizeMax)
        } else {
            assert!(zfh.frameType == ZSTD_skippableFrame);
            /* Add the entire skippable frame size to our margin. */
            margin += compressedSize;
        }

        src = &src[compressedSize as usize..];
    }

    /* Add the max block size back to the margin. */
    margin += maxBlockSize as size_t;

    margin
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_insertBlock))]
pub unsafe extern "C" fn ZSTD_insertBlock(
    dctx: *mut ZSTD_DCtx,
    blockStart: *const core::ffi::c_void,
    blockSize: size_t,
) -> size_t {
    ZSTD_checkContinuity(dctx, blockStart, blockSize);
    (*dctx).previousDstEnd =
        (blockStart as *const core::ffi::c_char).add(blockSize) as *const core::ffi::c_void;
    blockSize
}
unsafe fn ZSTD_copyRawBlock(
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    if srcSize > dstCapacity {
        return Error::dstSize_tooSmall.to_error_code();
    }
    if dst.is_null() {
        if srcSize == 0 {
            return 0;
        }
        return Error::dstBuffer_null.to_error_code();
    }
    libc::memmove(dst, src, srcSize as libc::size_t);
    srcSize
}
unsafe fn ZSTD_setRleBlock(
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    b: u8,
    regenSize: size_t,
) -> size_t {
    if regenSize > dstCapacity {
        return Error::dstSize_tooSmall.to_error_code();
    }
    if dst.is_null() {
        if regenSize == 0 {
            return 0;
        }
        return Error::dstBuffer_null.to_error_code();
    }
    ptr::write_bytes(dst, b, regenSize);
    regenSize
}
unsafe fn ZSTD_DCtx_trace_end(
    dctx: *const ZSTD_DCtx,
    uncompressedSize: u64,
    compressedSize: u64,
    streaming: core::ffi::c_int,
) {
    if (*dctx).traceCtx != 0 {
        let mut trace = ZSTD_Trace {
            version: 0,
            streaming: 0,
            dictionaryID: 0,
            dictionaryIsCold: 0,
            dictionarySize: 0,
            uncompressedSize: 0,
            compressedSize: 0,
            params: core::ptr::null::<ZSTD_CCtx_params_s>(),
            cctx: core::ptr::null::<ZSTD_CCtx_s>(),
            dctx: core::ptr::null::<ZSTD_DCtx_s>(),
        };
        ptr::write_bytes(
            &mut trace as *mut ZSTD_Trace as *mut u8,
            0,
            ::core::mem::size_of::<ZSTD_Trace>(),
        );
        trace.version = ZSTD_VERSION_NUMBER as core::ffi::c_uint;
        trace.streaming = streaming;
        if !((*dctx).ddict).is_null() {
            trace.dictionaryID = ZSTD_getDictID_fromDDict((*dctx).ddict);
            trace.dictionarySize = ZSTD_DDict_dictSize((*dctx).ddict);
            trace.dictionaryIsCold = (*dctx).ddictIsCold;
        }
        trace.uncompressedSize = uncompressedSize as size_t;
        trace.compressedSize = compressedSize as size_t;
        trace.dctx = dctx;
        ZSTD_trace_decompress_end((*dctx).traceCtx, &mut trace);
    }
}
unsafe fn ZSTD_decompressFrame(
    dctx: *mut ZSTD_DCtx,
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    srcPtr: &mut &[u8],
) -> size_t {
    let ilen = srcPtr.len();
    let ip = srcPtr;
    let ostart = dst as *mut u8;
    let oend = if dstCapacity != 0 {
        ostart.add(dstCapacity)
    } else {
        ostart
    };
    let mut op = ostart;
    if ip.len()
        < (match (*dctx).format {
            Format::ZSTD_f_zstd1 => 6usize,
            Format::ZSTD_f_zstd1_magicless => 2,
        })
        .wrapping_add(ZSTD_blockHeaderSize)
    {
        return Error::srcSize_wrong.to_error_code();
    }
    let frameHeaderSize = frame_header_size_internal(ip, (*dctx).format);
    if ERR_isError(frameHeaderSize) {
        return frameHeaderSize;
    }
    if ip.len() < frameHeaderSize.wrapping_add(ZSTD_blockHeaderSize) {
        return Error::srcSize_wrong.to_error_code();
    }
    let err_code = ZSTD_decodeFrameHeader(dctx, &ip[..frameHeaderSize]);
    if ERR_isError(err_code) {
        return err_code;
    }
    *ip = &ip[frameHeaderSize..];
    if (*dctx).maxBlockSizeParam != 0 {
        (*dctx).fParams.blockSizeMax =
            if (*dctx).fParams.blockSizeMax < (*dctx).maxBlockSizeParam as core::ffi::c_uint {
                (*dctx).fParams.blockSizeMax
            } else {
                (*dctx).maxBlockSizeParam as core::ffi::c_uint
            };
    }
    loop {
        let mut oBlockEnd = oend;
        let mut decodedSize: size_t = 0;

        let (blockProperties, cBlockSize) = match getc_block_size(ip) {
            Ok(ret) => ret,
            Err(e) => return e.to_error_code(),
        };

        *ip = &ip[ZSTD_blockHeaderSize..];
        if cBlockSize > ip.len() {
            return Error::srcSize_wrong.to_error_code();
        }
        if ip.as_ptr() >= op as *const u8 && ip.as_ptr() < oBlockEnd as *const u8 {
            oBlockEnd = op.offset(ip.as_ptr().offset_from(op) as core::ffi::c_long as isize);
        }
        match blockProperties.blockType {
            BlockType::Raw => {
                decodedSize = ZSTD_copyRawBlock(
                    op as *mut core::ffi::c_void,
                    oend.offset_from(op) as size_t,
                    ip.as_ptr().cast(),
                    cBlockSize,
                );
            }
            BlockType::Rle => {
                decodedSize = ZSTD_setRleBlock(
                    op as *mut core::ffi::c_void,
                    oBlockEnd.offset_from(op) as size_t,
                    ip[0],
                    blockProperties.origSize as size_t,
                );
            }
            BlockType::Compressed => {
                decodedSize = ZSTD_decompressBlock_internal(
                    dctx,
                    op as *mut core::ffi::c_void,
                    oBlockEnd.offset_from(op) as size_t,
                    ip.as_ptr().cast(),
                    cBlockSize,
                    not_streaming,
                );
            }
            BlockType::Reserved => {
                return Error::corruption_detected.to_error_code();
            }
        }
        let err_code_0 = decodedSize;
        if ERR_isError(err_code_0) {
            return err_code_0;
        }
        if (*dctx).validateChecksum != 0 {
            ZSTD_XXH64_update(
                &mut (*dctx).xxhState,
                op as *const core::ffi::c_void,
                decodedSize,
            );
        }
        if decodedSize != 0 {
            op = op.add(decodedSize);
        }
        *ip = &ip[cBlockSize..];
        if blockProperties.lastBlock != 0 {
            break;
        }
    }
    if (*dctx).fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
        && op.offset_from(ostart) as core::ffi::c_long as u64 as core::ffi::c_ulonglong
            != (*dctx).fParams.frameContentSize
    {
        return Error::corruption_detected.to_error_code();
    }
    if (*dctx).fParams.checksumFlag != 0 {
        let [a, b, c, d, ..] = **ip else {
            return Error::checksum_wrong.to_error_code();
        };

        if (*dctx).forceIgnoreChecksum == 0 {
            if u32::from_le_bytes([a, b, c, d]) != ZSTD_XXH64_digest(&mut (*dctx).xxhState) as u32 {
                return Error::checksum_wrong.to_error_code();
            }
        }

        *ip = &ip[4..];
    }

    ZSTD_DCtx_trace_end(
        dctx,
        op.offset_from(ostart) as core::ffi::c_long as u64,
        (ilen - ip.len()) as u64,
        0,
    );

    op.offset_from(ostart) as size_t
}

unsafe fn ZSTD_decompressMultiFrame(
    dctx: *mut ZSTD_DCtx,
    mut dst: *mut core::ffi::c_void,
    mut dstCapacity: size_t,
    mut src: &[u8],
    mut dict: *const core::ffi::c_void,
    mut dictSize: size_t,
    ddict: Option<&ZSTD_DDict>,
) -> size_t {
    let dststart = dst;
    let mut more_than_one_frame = false;

    if let Some(ddict) = ddict {
        dict = ZSTD_DDict_dictContent(ddict);
        dictSize = ZSTD_DDict_dictSize(ddict);
    }

    while src.len() >= ZSTD_startingInputLength((*dctx).format) {
        if (*dctx).format == Format::ZSTD_f_zstd1 && is_legacy(src) != 0 {
            let frameSize;
            {
                let srcSize = src.len();
                let src = src.as_ptr().cast();

                let mut decodedSize: size_t = 0;
                frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
                if ERR_isError(frameSize) {
                    return frameSize;
                }
                if (*dctx).staticSize != 0 {
                    return Error::memory_allocation.to_error_code();
                }
                decodedSize =
                    ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
                if ERR_isError(decodedSize) {
                    return decodedSize;
                }
                let expectedSize = ZSTD_getFrameContentSize(src, srcSize);
                if expectedSize == ZSTD_CONTENTSIZE_ERROR {
                    return Error::corruption_detected.to_error_code();
                }
                if expectedSize != ZSTD_CONTENTSIZE_UNKNOWN
                    && expectedSize != decodedSize as core::ffi::c_ulonglong
                {
                    return Error::corruption_detected.to_error_code();
                }
                dst = (dst as *mut u8).add(decodedSize) as *mut core::ffi::c_void;
                dstCapacity = dstCapacity.wrapping_sub(decodedSize);
            }
            src = &src[frameSize..];
        } else {
            if (*dctx).format == Format::ZSTD_f_zstd1 && src.len() >= 4 {
                let magicNumber = u32::from_le_bytes(*src.first_chunk().unwrap());
                if magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK
                    == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint
                {
                    let skippableSize = read_skippable_frame_size(src);
                    let err_code = skippableSize;
                    if ERR_isError(err_code) {
                        return err_code;
                    }
                    src = &src[skippableSize..];
                    continue;
                }
            }
            if let Some(ddict) = ddict {
                let err_code_0 = ZSTD_decompressBegin_usingDDict(dctx, ddict);
                if ERR_isError(err_code_0) {
                    return err_code_0;
                }
            } else {
                let err_code_1 = ZSTD_decompressBegin_usingDict(dctx, dict, dictSize);
                if ERR_isError(err_code_1) {
                    return err_code_1;
                }
            }
            ZSTD_checkContinuity(dctx, dst, dstCapacity);
            let res = ZSTD_decompressFrame(dctx, dst, dstCapacity, &mut src);
            if ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown && more_than_one_frame {
                return Error::srcSize_wrong.to_error_code();
            }
            if ERR_isError(res) {
                return res;
            }
            if res != 0 {
                dst = (dst as *mut u8).add(res) as *mut core::ffi::c_void;
            }
            dstCapacity = dstCapacity.wrapping_sub(res);
            more_than_one_frame = true;
        }
    }

    if !src.is_empty() {
        return Error::srcSize_wrong.to_error_code();
    }

    (dst as *mut u8).offset_from(dststart as *mut u8) as size_t
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompress_usingDict))]
pub unsafe extern "C" fn ZSTD_decompress_usingDict(
    dctx: *mut ZSTD_DCtx,
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
    dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    let src = if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast::<u8>(), srcSize)
    };
    ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, dict, dictSize, None)
}

unsafe fn ZSTD_getDDict(dctx: *mut ZSTD_DCtx) -> *const ZSTD_DDict {
    match (*dctx).dictUses as core::ffi::c_int {
        -1 => (*dctx).ddict,
        1 => {
            (*dctx).dictUses = ZSTD_dont_use;
            (*dctx).ddict
        }
        0 | _ => {
            ZSTD_clearDict(dctx);
            core::ptr::null()
        }
    }
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressDCtx))]
pub unsafe extern "C" fn ZSTD_decompressDCtx(
    dctx: *mut ZSTD_DCtx,
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx))
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompress))]
pub unsafe extern "C" fn ZSTD_decompress(
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    let mut regenSize: size_t = 0;
    let dctx = ZSTD_createDCtx_internal(ZSTD_defaultCMem);
    if dctx.is_null() {
        return Error::memory_allocation.to_error_code();
    }
    regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
    ZSTD_freeDCtx(dctx);
    regenSize
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_nextSrcSizeToDecompress))]
pub unsafe extern "C" fn ZSTD_nextSrcSizeToDecompress(dctx: *mut ZSTD_DCtx) -> size_t {
    (*dctx).expected
}

unsafe fn ZSTD_nextSrcSizeToDecompressWithInputSize(
    dctx: *mut ZSTD_DCtx,
    inputSize: size_t,
) -> size_t {
    match (*dctx).stage {
        DecompressStage::DecompressBlock | DecompressStage::DecompressLastBlock => {
            Ord::clamp(1, inputSize, (*dctx).expected)
        }
        _ => (*dctx).expected,
    }
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_nextInputType))]
pub unsafe extern "C" fn ZSTD_nextInputType(dctx: *mut ZSTD_DCtx) -> ZSTD_nextInputType_e {
    (*dctx).stage.to_next_input_type() as ZSTD_nextInputType_e
}

unsafe fn ZSTD_isSkipFrame(dctx: *mut ZSTD_DCtx) -> core::ffi::c_int {
    matches!((*dctx).stage, DecompressStage::SkipFrame) as core::ffi::c_int
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressContinue))]
pub unsafe extern "C" fn ZSTD_decompressContinue(
    dctx: *mut ZSTD_DCtx,
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    if srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize) {
        return Error::srcSize_wrong.to_error_code();
    }
    ZSTD_checkContinuity(dctx, dst, dstCapacity);
    (*dctx).processedCSize = ((*dctx).processedCSize as size_t).wrapping_add(srcSize) as u64;
    match (*dctx).stage {
        DecompressStage::GetFrameHeaderSize => {
            if (*dctx).format == Format::ZSTD_f_zstd1
                && MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK
                    == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint
            {
                libc::memcpy(
                    ((*dctx).headerBuffer).as_mut_ptr() as *mut core::ffi::c_void,
                    src,
                    srcSize as libc::size_t,
                );
                (*dctx).expected = (ZSTD_SKIPPABLEHEADERSIZE as size_t).wrapping_sub(srcSize);
                (*dctx).stage = DecompressStage::DecodeSkippableHeader;
                return 0;
            }
            let src_slice = core::slice::from_raw_parts(src.cast(), srcSize);
            (*dctx).headerSize = frame_header_size_internal(src_slice, (*dctx).format);
            if ERR_isError((*dctx).headerSize) {
                return (*dctx).headerSize;
            }
            libc::memcpy(
                ((*dctx).headerBuffer).as_mut_ptr() as *mut core::ffi::c_void,
                src,
                srcSize as libc::size_t,
            );
            (*dctx).expected = ((*dctx).headerSize).wrapping_sub(srcSize);
            (*dctx).stage = DecompressStage::DecodeFrameHeader;
            0
        }
        DecompressStage::DecodeFrameHeader => {
            libc::memcpy(
                ((*dctx).headerBuffer)
                    .as_mut_ptr()
                    .add(((*dctx).headerSize).wrapping_sub(srcSize))
                    as *mut core::ffi::c_void,
                src,
                srcSize as libc::size_t,
            );
            let err_code =
                ZSTD_decodeFrameHeader(dctx, &(&(*dctx).headerBuffer)[..(*dctx).headerSize]);
            if ERR_isError(err_code) {
                return err_code;
            }
            (*dctx).expected = ZSTD_blockHeaderSize;
            (*dctx).stage = DecompressStage::DecodeBlockHeader;
            0
        }
        DecompressStage::DecodeBlockHeader => {
            let mut bp = blockProperties_t {
                blockType: BlockType::Raw,
                lastBlock: 0,
                origSize: 0,
            };
            let cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &mut bp);
            if ERR_isError(cBlockSize) {
                return cBlockSize;
            }
            if cBlockSize > (*dctx).fParams.blockSizeMax as size_t {
                return Error::corruption_detected.to_error_code();
            }
            (*dctx).expected = cBlockSize;
            (*dctx).bType = bp.blockType;
            (*dctx).rleSize = bp.origSize as size_t;
            if cBlockSize != 0 {
                (*dctx).stage = match bp.lastBlock {
                    0 => DecompressStage::DecompressBlock,
                    _ => DecompressStage::DecompressLastBlock,
                };
                return 0;
            }
            if bp.lastBlock != 0 {
                if (*dctx).fParams.checksumFlag != 0 {
                    (*dctx).expected = 4;
                    (*dctx).stage = DecompressStage::CheckChecksum;
                } else {
                    (*dctx).expected = 0;
                    (*dctx).stage = DecompressStage::GetFrameHeaderSize;
                }
            } else {
                (*dctx).expected = ZSTD_blockHeaderSize;
                (*dctx).stage = DecompressStage::DecodeBlockHeader;
            }
            0
        }

        DecompressStage::DecompressBlock | DecompressStage::DecompressLastBlock => {
            let mut rSize: size_t = 0;
            match (*dctx).bType {
                BlockType::Compressed => {
                    rSize = ZSTD_decompressBlock_internal(
                        dctx,
                        dst,
                        dstCapacity,
                        src,
                        srcSize,
                        is_streaming,
                    );
                    (*dctx).expected = 0;
                }
                BlockType::Raw => {
                    rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
                    let err_code_0 = rSize;
                    if ERR_isError(err_code_0) {
                        return err_code_0;
                    }
                    (*dctx).expected = ((*dctx).expected).wrapping_sub(rSize);
                }
                BlockType::Rle => {
                    rSize =
                        ZSTD_setRleBlock(dst, dstCapacity, *(src as *const u8), (*dctx).rleSize);
                    (*dctx).expected = 0;
                }
                BlockType::Reserved => {
                    return Error::corruption_detected.to_error_code();
                }
            }
            let err_code_1 = rSize;
            if ERR_isError(err_code_1) {
                return err_code_1;
            }
            if rSize > (*dctx).fParams.blockSizeMax as size_t {
                return Error::corruption_detected.to_error_code();
            }
            (*dctx).decodedSize = ((*dctx).decodedSize as size_t).wrapping_add(rSize) as u64 as u64;
            if (*dctx).validateChecksum != 0 {
                ZSTD_XXH64_update(&mut (*dctx).xxhState, dst, rSize as usize);
            }
            (*dctx).previousDstEnd =
                (dst as *mut core::ffi::c_char).add(rSize) as *const core::ffi::c_void;
            if (*dctx).expected > 0 {
                return rSize;
            }
            if (*dctx).stage == DecompressStage::DecompressLastBlock {
                if (*dctx).fParams.frameContentSize != (0 as core::ffi::c_ulonglong).wrapping_sub(1)
                    && (*dctx).decodedSize as core::ffi::c_ulonglong
                        != (*dctx).fParams.frameContentSize
                {
                    return Error::corruption_detected.to_error_code();
                }
                if (*dctx).fParams.checksumFlag != 0 {
                    (*dctx).expected = 4;
                    (*dctx).stage = DecompressStage::CheckChecksum;
                } else {
                    ZSTD_DCtx_trace_end(dctx, (*dctx).decodedSize, (*dctx).processedCSize, 1);
                    (*dctx).expected = 0;
                    (*dctx).stage = DecompressStage::GetFrameHeaderSize;
                }
            } else {
                (*dctx).stage = DecompressStage::DecodeBlockHeader;
                (*dctx).expected = ZSTD_blockHeaderSize;
            }
            rSize
        }
        DecompressStage::CheckChecksum => {
            if (*dctx).validateChecksum != 0 {
                let h32 = ZSTD_XXH64_digest(&mut (*dctx).xxhState) as u32;
                let check32 = MEM_readLE32(src);
                if check32 != h32 {
                    return Error::checksum_wrong.to_error_code();
                }
            }
            ZSTD_DCtx_trace_end(dctx, (*dctx).decodedSize, (*dctx).processedCSize, 1);
            (*dctx).expected = 0;
            (*dctx).stage = DecompressStage::GetFrameHeaderSize;
            0
        }
        DecompressStage::DecodeSkippableHeader => {
            libc::memcpy(
                ((*dctx).headerBuffer)
                    .as_mut_ptr()
                    .add((8 as size_t).wrapping_sub(srcSize))
                    as *mut core::ffi::c_void,
                src,
                srcSize as libc::size_t,
            );
            (*dctx).expected =
                MEM_readLE32(((*dctx).headerBuffer).as_mut_ptr().add(ZSTD_FRAMEIDSIZE)
                    as *const core::ffi::c_void) as size_t;
            (*dctx).stage = DecompressStage::SkipFrame;
            0
        }
        DecompressStage::SkipFrame => {
            (*dctx).expected = 0;
            (*dctx).stage = DecompressStage::GetFrameHeaderSize;
            0
        }
    }
}

pub unsafe fn ZSTD_loadDEntropy(entropy: &mut ZSTD_entropyDTables_t, dict: &[u8]) -> size_t {
    let Some((_, mut dictPtr)) = dict.split_at_checked(8) else {
        return Error::dictionary_corrupted.to_error_code();
    };

    const _: () = assert!(
        size_of::<crate::lib::decompress::SymbolTable<512>>()
            >= size_of::<HUF_ReadDTableX2_Workspace>()
    );
    const _: () = assert!(
        align_of::<crate::lib::decompress::SymbolTable<512>>()
            >= align_of::<HUF_ReadDTableX2_Workspace>()
    );

    let workspace = &mut entropy.LLTable;
    let wksp: &mut HUF_ReadDTableX2_Workspace = unsafe { core::mem::transmute(workspace) };

    let hSize = HUF_readDTableX2_wksp(&mut entropy.hufTable, dictPtr, wksp, 0);
    if ERR_isError(hSize) {
        return Error::dictionary_corrupted.to_error_code();
    }

    dictPtr = &dictPtr[hSize..];
    let mut offcodeNCount: [core::ffi::c_short; 32] = [0; 32];
    let mut offcodeMaxValue = MaxOff as core::ffi::c_uint;
    let mut offcodeLog: core::ffi::c_uint = 0;
    let offcodeHeaderSize = FSE_readNCount_slice(
        &mut offcodeNCount,
        &mut offcodeMaxValue,
        &mut offcodeLog,
        dictPtr,
    );

    let Ok(offcodeHeaderSize) = offcodeHeaderSize else {
        return Error::dictionary_corrupted.to_error_code();
    };
    if offcodeMaxValue > 31 {
        return Error::dictionary_corrupted.to_error_code();
    }
    if offcodeLog > 8 {
        return Error::dictionary_corrupted.to_error_code();
    }
    ZSTD_buildFSETable(
        &mut entropy.OFTable,
        &offcodeNCount[..=offcodeMaxValue as usize],
        &OF_base,
        &OF_bits,
        offcodeLog,
        &mut entropy.workspace,
        false,
    );
    dictPtr = &dictPtr[offcodeHeaderSize..];
    let mut matchlengthNCount: [core::ffi::c_short; 53] = [0; 53];
    let mut matchlengthMaxValue = MaxML as core::ffi::c_uint;
    let mut matchlengthLog: core::ffi::c_uint = 0;
    let matchlengthHeaderSize = FSE_readNCount_slice(
        &mut matchlengthNCount,
        &mut matchlengthMaxValue,
        &mut matchlengthLog,
        dictPtr,
    );
    let Ok(matchlengthHeaderSize) = matchlengthHeaderSize else {
        return Error::dictionary_corrupted.to_error_code();
    };
    if matchlengthMaxValue > 52 {
        return Error::dictionary_corrupted.to_error_code();
    }
    if matchlengthLog > 9 {
        return Error::dictionary_corrupted.to_error_code();
    }
    ZSTD_buildFSETable(
        &mut entropy.MLTable,
        &matchlengthNCount[..=matchlengthMaxValue as usize],
        &ML_base,
        &ML_bits,
        matchlengthLog,
        &mut entropy.workspace,
        false,
    );
    dictPtr = &dictPtr[matchlengthHeaderSize..];
    let mut litlengthNCount: [core::ffi::c_short; 36] = [0; 36];
    let mut litlengthMaxValue = MaxLL as core::ffi::c_uint;
    let mut litlengthLog: core::ffi::c_uint = 0;
    let litlengthHeaderSize = FSE_readNCount_slice(
        &mut litlengthNCount,
        &mut litlengthMaxValue,
        &mut litlengthLog,
        dictPtr,
    );
    let Ok(litlengthHeaderSize) = litlengthHeaderSize else {
        return Error::dictionary_corrupted.to_error_code();
    };
    if litlengthMaxValue > 35 {
        return Error::dictionary_corrupted.to_error_code();
    }
    if litlengthLog > 9 {
        return Error::dictionary_corrupted.to_error_code();
    }
    ZSTD_buildFSETable(
        &mut entropy.LLTable,
        &litlengthNCount[..=litlengthMaxValue as usize],
        &LL_base,
        &LL_bits,
        litlengthLog,
        &mut entropy.workspace,
        false,
    );
    dictPtr = &dictPtr[litlengthHeaderSize..];
    let Some((chunk, dict_content)) = dictPtr.split_first_chunk::<12>() else {
        return Error::dictionary_corrupted.to_error_code();
    };

    let dict_content_size = dict_content.len();
    for (i, rep) in chunk.as_chunks::<4>().0.iter().enumerate() {
        let rep = u32::from_le_bytes(*rep);
        if rep == 0 || rep as size_t > dict_content_size {
            return Error::dictionary_corrupted.to_error_code();
        }
        entropy.rep[i] = rep;
    }

    dict.len() - dict_content_size
}

unsafe fn ZSTD_refDictContent(dctx: *mut ZSTD_DCtx, dict: &[u8]) -> size_t {
    (*dctx).dictEnd = (*dctx).previousDstEnd;
    (*dctx).virtualStart = dict
        .as_ptr()
        .sub((((*dctx).previousDstEnd).byte_offset_from((*dctx).prefixStart)) as usize)
        .cast();
    (*dctx).prefixStart = dict.as_ptr().cast();
    (*dctx).previousDstEnd = dict.as_ptr_range().end.cast();

    0
}

unsafe fn ZSTD_decompress_insertDictionary(dctx: *mut ZSTD_DCtx, dict: &[u8]) -> size_t {
    let ([magic, dict_id, ..], _) = dict.as_chunks::<4>() else {
        return ZSTD_refDictContent(dctx, dict);
    };

    let magic = u32::from_le_bytes(*magic);
    if magic != ZSTD_MAGIC_DICTIONARY {
        return ZSTD_refDictContent(dctx, dict);
    }
    (*dctx).dictID = u32::from_le_bytes(*dict_id);
    let eSize = ZSTD_loadDEntropy(&mut (*dctx).entropy, dict);
    if ERR_isError(eSize) {
        return Error::dictionary_corrupted.to_error_code();
    }

    (*dctx).fseEntropy = 1;
    (*dctx).litEntropy = (*dctx).fseEntropy;

    ZSTD_refDictContent(dctx, &dict[eSize..])
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressBegin))]
pub unsafe extern "C" fn ZSTD_decompressBegin(dctx: *mut ZSTD_DCtx) -> size_t {
    (*dctx).traceCtx = ZSTD_trace_decompress_begin(dctx);
    (*dctx).expected = ZSTD_startingInputLength((*dctx).format);
    (*dctx).stage = DecompressStage::GetFrameHeaderSize;
    (*dctx).processedCSize = 0;
    (*dctx).decodedSize = 0;
    (*dctx).previousDstEnd = core::ptr::null();
    (*dctx).prefixStart = core::ptr::null();
    (*dctx).virtualStart = core::ptr::null();
    (*dctx).dictEnd = core::ptr::null();
    (*dctx).entropy.hufTable.description = DTableDesc::from_u32(12 * 0x1000001);
    (*dctx).fseEntropy = 0;
    (*dctx).litEntropy = (*dctx).fseEntropy;
    (*dctx).dictID = 0;
    (*dctx).bType = BlockType::Reserved;
    (*dctx).isFrameDecompression = 1;
    libc::memcpy(
        ((*dctx).entropy.rep).as_mut_ptr() as *mut core::ffi::c_void,
        repStartValue.as_ptr() as *const core::ffi::c_void,
        ::core::mem::size_of::<[u32; 3]>() as libc::size_t,
    );
    (*dctx).LLTptr = ((*dctx).entropy.LLTable).as_mut_ptr();
    (*dctx).MLTptr = ((*dctx).entropy.MLTable).as_mut_ptr();
    (*dctx).OFTptr = ((*dctx).entropy.OFTable).as_mut_ptr();
    (*dctx).HUFptr = &raw const (*dctx).entropy.hufTable;
    0
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressBegin_usingDict))]
pub unsafe extern "C" fn ZSTD_decompressBegin_usingDict(
    dctx: *mut ZSTD_DCtx,
    dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    let err_code = ZSTD_decompressBegin(dctx);
    if ERR_isError(err_code) {
        return err_code;
    }

    if dict.is_null() || dictSize == 0 {
        return 0;
    }

    let dict = core::slice::from_raw_parts(dict.cast::<u8>(), dictSize);
    if ERR_isError(ZSTD_decompress_insertDictionary(dctx, dict)) {
        return Error::dictionary_corrupted.to_error_code();
    }

    0
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressBegin_usingDDict))]
pub unsafe extern "C" fn ZSTD_decompressBegin_usingDDict(
    dctx: *mut ZSTD_DCtx,
    ddict: *const ZSTD_DDict,
) -> size_t {
    if !ddict.is_null() {
        let dictStart = ZSTD_DDict_dictContent(ddict) as *const core::ffi::c_char;
        let dictSize = ZSTD_DDict_dictSize(ddict);
        let dictEnd = dictStart.add(dictSize) as *const core::ffi::c_void;
        (*dctx).ddictIsCold = ((*dctx).dictEnd != dictEnd) as core::ffi::c_int;
    }
    let err_code = ZSTD_decompressBegin(dctx);
    if ERR_isError(err_code) {
        return err_code;
    }
    if !ddict.is_null() {
        ZSTD_copyDDictParameters(dctx, ddict);
    }
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getDictID_fromDict))]
pub unsafe extern "C" fn ZSTD_getDictID_fromDict(
    dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> core::ffi::c_uint {
    if dictSize < 8 {
        return 0;
    }
    if MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY {
        return 0;
    }
    MEM_readLE32(
        (dict as *const core::ffi::c_char).add(ZSTD_FRAMEIDSIZE) as *const core::ffi::c_void
    )
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_getDictID_fromFrame))]
pub unsafe extern "C" fn ZSTD_getDictID_fromFrame(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> core::ffi::c_uint {
    let mut zfp = {
        ZSTD_FrameHeader {
            frameContentSize: 0,
            windowSize: 0,
            blockSizeMax: 0,
            frameType: ZSTD_frame,
            headerSize: 0,
            dictID: 0,
            checksumFlag: 0,
            _reserved1: 0,
            _reserved2: 0,
        }
    };
    let hError = ZSTD_getFrameHeader(&mut zfp, src, srcSize);
    if ERR_isError(hError) {
        return 0;
    }
    zfp.dictID
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompress_usingDDict))]
pub unsafe extern "C" fn ZSTD_decompress_usingDDict(
    dctx: *mut ZSTD_DCtx,
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
    ddict: *const ZSTD_DDict,
) -> size_t {
    let src = if src.is_null() {
        &[]
    } else {
        core::slice::from_raw_parts(src.cast::<u8>(), srcSize)
    };

    ZSTD_decompressMultiFrame(
        dctx,
        dst,
        dstCapacity,
        src,
        core::ptr::null(),
        0,
        ddict.as_ref(),
    )
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createDStream))]
pub unsafe extern "C" fn ZSTD_createDStream() -> *mut ZSTD_DStream {
    ZSTD_createDCtx_internal(ZSTD_defaultCMem)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initStaticDStream))]
pub unsafe extern "C" fn ZSTD_initStaticDStream(
    workspace: *mut core::ffi::c_void,
    workspaceSize: size_t,
) -> *mut ZSTD_DStream {
    ZSTD_initStaticDCtx(workspace, workspaceSize)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_createDStream_advanced))]
pub unsafe extern "C" fn ZSTD_createDStream_advanced(
    customMem: ZSTD_customMem,
) -> *mut ZSTD_DStream {
    ZSTD_createDCtx_internal(customMem)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_freeDStream))]
pub unsafe extern "C" fn ZSTD_freeDStream(zds: *mut ZSTD_DStream) -> size_t {
    ZSTD_freeDCtx(zds)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DStreamInSize))]
pub unsafe extern "C" fn ZSTD_DStreamInSize() -> size_t {
    (ZSTD_BLOCKSIZE_MAX as size_t).wrapping_add(ZSTD_blockHeaderSize)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DStreamOutSize))]
pub unsafe extern "C" fn ZSTD_DStreamOutSize() -> size_t {
    ZSTD_BLOCKSIZE_MAX as size_t
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_loadDictionary_advanced))]
pub unsafe extern "C" fn ZSTD_DCtx_loadDictionary_advanced(
    dctx: *mut ZSTD_DCtx,
    dict: *const core::ffi::c_void,
    dictSize: size_t,
    dictLoadMethod: ZSTD_dictLoadMethod_e,
    dictContentType: ZSTD_dictContentType_e,
) -> size_t {
    if (*dctx).streamStage != StreamStage::Init {
        return Error::stage_wrong.to_error_code();
    }
    ZSTD_clearDict(dctx);
    if !dict.is_null() && dictSize != 0 {
        (*dctx).ddictLocal = ZSTD_createDDict_advanced(
            dict,
            dictSize,
            dictLoadMethod,
            dictContentType,
            (*dctx).customMem,
        );
        if ((*dctx).ddictLocal).is_null() {
            return Error::memory_allocation.to_error_code();
        }
        (*dctx).ddict = (*dctx).ddictLocal;
        (*dctx).dictUses = ZSTD_use_indefinitely;
    }
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_loadDictionary_byReference))]
pub unsafe extern "C" fn ZSTD_DCtx_loadDictionary_byReference(
    dctx: *mut ZSTD_DCtx,
    dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_loadDictionary))]
pub unsafe extern "C" fn ZSTD_DCtx_loadDictionary(
    dctx: *mut ZSTD_DCtx,
    dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_refPrefix_advanced))]
pub unsafe extern "C" fn ZSTD_DCtx_refPrefix_advanced(
    dctx: *mut ZSTD_DCtx,
    prefix: *const core::ffi::c_void,
    prefixSize: size_t,
    dictContentType: ZSTD_dictContentType_e,
) -> size_t {
    let err_code = ZSTD_DCtx_loadDictionary_advanced(
        dctx,
        prefix,
        prefixSize,
        ZSTD_dlm_byRef,
        dictContentType,
    );
    if ERR_isError(err_code) {
        return err_code;
    }
    (*dctx).dictUses = ZSTD_use_once;
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_refPrefix))]
pub unsafe extern "C" fn ZSTD_DCtx_refPrefix(
    dctx: *mut ZSTD_DCtx,
    prefix: *const core::ffi::c_void,
    prefixSize: size_t,
) -> size_t {
    ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initDStream_usingDict))]
pub unsafe extern "C" fn ZSTD_initDStream_usingDict(
    zds: *mut ZSTD_DStream,
    dict: *const core::ffi::c_void,
    dictSize: size_t,
) -> size_t {
    let err_code = ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
    if ERR_isError(err_code) {
        return err_code;
    }
    let err_code_0 = ZSTD_DCtx_loadDictionary(zds, dict, dictSize);
    if ERR_isError(err_code_0) {
        return err_code_0;
    }
    ZSTD_startingInputLength((*zds).format)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initDStream))]
pub unsafe extern "C" fn ZSTD_initDStream(zds: *mut ZSTD_DStream) -> size_t {
    let err_code = ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
    if ERR_isError(err_code) {
        return err_code;
    }
    let err_code_0 = ZSTD_DCtx_refDDict(zds, core::ptr::null::<ZSTD_DDict>());
    if ERR_isError(err_code_0) {
        return err_code_0;
    }
    ZSTD_startingInputLength((*zds).format)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_initDStream_usingDDict))]
pub unsafe extern "C" fn ZSTD_initDStream_usingDDict(
    dctx: *mut ZSTD_DStream,
    ddict: *const ZSTD_DDict,
) -> size_t {
    let err_code = ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only);
    if ERR_isError(err_code) {
        return err_code;
    }
    let err_code_0 = ZSTD_DCtx_refDDict(dctx, ddict);
    if ERR_isError(err_code_0) {
        return err_code_0;
    }
    ZSTD_startingInputLength((*dctx).format)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_resetDStream))]
pub unsafe extern "C" fn ZSTD_resetDStream(dctx: *mut ZSTD_DStream) -> size_t {
    let err_code = ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only);
    if ERR_isError(err_code) {
        return err_code;
    }
    ZSTD_startingInputLength((*dctx).format)
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_refDDict))]
pub unsafe extern "C" fn ZSTD_DCtx_refDDict(
    dctx: *mut ZSTD_DCtx,
    ddict: *const ZSTD_DDict,
) -> size_t {
    if (*dctx).streamStage != StreamStage::Init {
        return Error::stage_wrong.to_error_code();
    }
    ZSTD_clearDict(dctx);

    if !ddict.is_null() {
        (*dctx).ddict = ddict;
        (*dctx).dictUses = ZSTD_use_indefinitely;
        if (*dctx).refMultipleDDicts == MultipleDDicts::Multiple {
            if ((*dctx).ddictSet).is_null() {
                (*dctx).ddictSet = ZSTD_createDDictHashSet((*dctx).customMem);
            }

            let Some(ddictSet) = (*dctx).ddictSet.as_mut() else {
                return Error::memory_allocation.to_error_code();
            };

            let err_code = ZSTD_DDictHashSet_addDDict(ddictSet, ddict, (*dctx).customMem);
            if ERR_isError(err_code) {
                return err_code;
            }
        }
    }

    0
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_setMaxWindowSize))]
pub unsafe extern "C" fn ZSTD_DCtx_setMaxWindowSize(
    dctx: *mut ZSTD_DCtx,
    maxWindowSize: size_t,
) -> size_t {
    let bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
    let min = (1) << bounds.lowerBound;
    let max = (1) << bounds.upperBound;
    if (*dctx).streamStage != StreamStage::Init {
        return Error::stage_wrong.to_error_code();
    }
    if maxWindowSize < min {
        return Error::parameter_outOfBound.to_error_code();
    }
    if maxWindowSize > max {
        return Error::parameter_outOfBound.to_error_code();
    }
    (*dctx).maxWindowSize = maxWindowSize;
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_setFormat))]
pub unsafe extern "C" fn ZSTD_DCtx_setFormat(
    dctx: *mut ZSTD_DCtx,
    format: ZSTD_format_e,
) -> size_t {
    ZSTD_DCtx_setParameter(
        dctx,
        ZSTD_d_format as ZSTD_dParameter,
        format as core::ffi::c_int,
    )
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_dParam_getBounds))]
pub unsafe extern "C" fn ZSTD_dParam_getBounds(dParam: ZSTD_dParameter) -> ZSTD_bounds {
    let mut bounds = {
        ZSTD_bounds {
            error: 0,
            lowerBound: 0,
            upperBound: 0,
        }
    };
    match dParam as core::ffi::c_uint {
        100 => {
            bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
            bounds.upperBound = if ::core::mem::size_of::<size_t>() == 4 {
                ZSTD_WINDOWLOG_MAX_32
            } else {
                ZSTD_WINDOWLOG_MAX_64
            };
            return bounds;
        }
        1000 => {
            bounds.lowerBound = Format::ZSTD_f_zstd1 as core::ffi::c_int;
            bounds.upperBound = Format::ZSTD_f_zstd1_magicless as core::ffi::c_int;
            return bounds;
        }
        1001 => {
            bounds.lowerBound = BufferMode::Buffered as core::ffi::c_int;
            bounds.upperBound = BufferMode::Stable as core::ffi::c_int;
            return bounds;
        }
        1002 => {
            bounds.lowerBound = ZSTD_d_validateChecksum as core::ffi::c_int;
            bounds.upperBound = ZSTD_d_ignoreChecksum as core::ffi::c_int;
            return bounds;
        }
        1003 => {
            bounds.lowerBound = MultipleDDicts::Single as core::ffi::c_int;
            bounds.upperBound = MultipleDDicts::Multiple as core::ffi::c_int;
            return bounds;
        }
        1004 => {
            bounds.lowerBound = 0;
            bounds.upperBound = 1;
            return bounds;
        }
        1005 => {
            bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN;
            bounds.upperBound = ZSTD_BLOCKSIZE_MAX;
            return bounds;
        }
        _ => {}
    }
    bounds.error = Error::parameter_unsupported.to_error_code();
    bounds
}
unsafe fn ZSTD_dParam_withinBounds(
    dParam: ZSTD_dParameter,
    value: core::ffi::c_int,
) -> core::ffi::c_int {
    let bounds = ZSTD_dParam_getBounds(dParam);
    if ERR_isError(bounds.error) {
        return 0;
    }
    if value < bounds.lowerBound {
        return 0;
    }
    if value > bounds.upperBound {
        return 0;
    }
    1
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_getParameter))]
pub unsafe extern "C" fn ZSTD_DCtx_getParameter(
    dctx: *mut ZSTD_DCtx,
    param: ZSTD_dParameter,
    value: *mut core::ffi::c_int,
) -> size_t {
    match param as core::ffi::c_uint {
        100 => {
            *value = (*dctx).maxWindowSize.ilog2() as i32;
            0
        }
        1000 => {
            *value = (*dctx).format as core::ffi::c_int;
            0
        }
        1001 => {
            *value = (*dctx).outBufferMode as core::ffi::c_int;
            0
        }
        1002 => {
            *value = (*dctx).forceIgnoreChecksum as core::ffi::c_int;
            0
        }
        1003 => {
            *value = (*dctx).refMultipleDDicts as core::ffi::c_int;
            0
        }
        1004 => {
            *value = (*dctx).disableHufAsm;
            0
        }
        1005 => {
            *value = (*dctx).maxBlockSizeParam;
            0
        }
        _ => Error::parameter_unsupported.to_error_code(),
    }
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_setParameter))]
pub unsafe extern "C" fn ZSTD_DCtx_setParameter(
    dctx: *mut ZSTD_DCtx,
    dParam: ZSTD_dParameter,
    mut value: core::ffi::c_int,
) -> size_t {
    if (*dctx).streamStage != StreamStage::Init {
        return Error::stage_wrong.to_error_code();
    }
    match dParam as core::ffi::c_uint {
        100 => {
            if value == 0 {
                value = ZSTD_WINDOWLOG_LIMIT_DEFAULT;
            }
            if ZSTD_dParam_withinBounds(ZSTD_d_windowLogMax, value) == 0 {
                return Error::parameter_outOfBound.to_error_code();
            }
            (*dctx).maxWindowSize = (1) << value;
            return 0;
        }
        1000 => {
            let Ok(format) = Format::try_from(value as ZSTD_format_e) else {
                return Error::parameter_outOfBound.to_error_code();
            };

            (*dctx).format = format;

            return 0;
        }
        1001 => {
            let Ok(value) = BufferMode::try_from(value as u32) else {
                return Error::parameter_outOfBound.to_error_code();
            };
            (*dctx).outBufferMode = value;
            return 0;
        }
        1002 => {
            if ZSTD_dParam_withinBounds(ZSTD_d_experimentalParam3, value) == 0 {
                return Error::parameter_outOfBound.to_error_code();
            }
            (*dctx).forceIgnoreChecksum = value as ZSTD_forceIgnoreChecksum_e;
            return 0;
        }
        1003 => {
            let Ok(value) = MultipleDDicts::try_from(value as u32) else {
                return Error::parameter_outOfBound.to_error_code();
            };
            if (*dctx).staticSize != 0 {
                return Error::parameter_unsupported.to_error_code();
            }
            (*dctx).refMultipleDDicts = value;
            return 0;
        }
        1004 => {
            if ZSTD_dParam_withinBounds(ZSTD_d_experimentalParam5, value) == 0 {
                return Error::parameter_outOfBound.to_error_code();
            }
            (*dctx).disableHufAsm = (value != 0) as core::ffi::c_int;
            return 0;
        }
        1005 => {
            if value != 0 && ZSTD_dParam_withinBounds(ZSTD_d_experimentalParam6, value) == 0 {
                return Error::parameter_outOfBound.to_error_code();
            }
            (*dctx).maxBlockSizeParam = value;
            return 0;
        }
        _ => {}
    }
    Error::parameter_unsupported.to_error_code()
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_DCtx_reset))]
pub unsafe extern "C" fn ZSTD_DCtx_reset(
    dctx: *mut ZSTD_DCtx,
    reset: ZSTD_ResetDirective,
) -> size_t {
    if reset as core::ffi::c_uint
        == ZSTD_reset_session_only as core::ffi::c_int as core::ffi::c_uint
        || reset as core::ffi::c_uint
            == ZSTD_reset_session_and_parameters as core::ffi::c_int as core::ffi::c_uint
    {
        (*dctx).streamStage = StreamStage::Init;
        (*dctx).noForwardProgress = 0;
        (*dctx).isFrameDecompression = 1;
    }
    if reset as core::ffi::c_uint == ZSTD_reset_parameters as core::ffi::c_int as core::ffi::c_uint
        || reset as core::ffi::c_uint
            == ZSTD_reset_session_and_parameters as core::ffi::c_int as core::ffi::c_uint
    {
        if (*dctx).streamStage != StreamStage::Init {
            return Error::stage_wrong.to_error_code();
        }
        ZSTD_clearDict(dctx);
        ZSTD_DCtx_resetParameters(dctx);
    }
    0
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_sizeof_DStream))]
pub unsafe extern "C" fn ZSTD_sizeof_DStream(dctx: *const ZSTD_DStream) -> size_t {
    ZSTD_sizeof_DCtx(dctx)
}
unsafe fn ZSTD_decodingBufferSize_internal(
    windowSize: core::ffi::c_ulonglong,
    frameContentSize: core::ffi::c_ulonglong,
    blockSizeMax: size_t,
) -> size_t {
    let blockSize = if ((if windowSize < ((1) << 17) as core::ffi::c_ulonglong {
        windowSize
    } else {
        ((1) << 17) as core::ffi::c_ulonglong
    }) as size_t)
        < blockSizeMax
    {
        (if windowSize < ((1) << 17) as core::ffi::c_ulonglong {
            windowSize
        } else {
            ((1) << 17) as core::ffi::c_ulonglong
        }) as size_t
    } else {
        blockSizeMax
    };
    let neededRBSize = windowSize
        .wrapping_add((blockSize * 2) as core::ffi::c_ulonglong)
        .wrapping_add((WILDCOPY_OVERLENGTH * 2) as core::ffi::c_ulonglong);
    let neededSize = if frameContentSize < neededRBSize {
        frameContentSize
    } else {
        neededRBSize
    };
    let minRBSize = neededSize as size_t;
    if minRBSize as core::ffi::c_ulonglong != neededSize {
        return Error::frameParameter_windowTooLarge.to_error_code();
    }
    minRBSize
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decodingBufferSize_min))]
pub unsafe extern "C" fn ZSTD_decodingBufferSize_min(
    windowSize: core::ffi::c_ulonglong,
    frameContentSize: core::ffi::c_ulonglong,
) -> size_t {
    ZSTD_decodingBufferSize_internal(windowSize, frameContentSize, ZSTD_BLOCKSIZE_MAX as size_t)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateDStreamSize))]
pub unsafe extern "C" fn ZSTD_estimateDStreamSize(windowSize: size_t) -> size_t {
    let blockSize = if windowSize < ((1) << 17) as size_t {
        windowSize
    } else {
        ((1) << 17) as size_t
    };
    let inBuffSize = blockSize;
    let outBuffSize = ZSTD_decodingBufferSize_min(
        windowSize as core::ffi::c_ulonglong,
        ZSTD_CONTENTSIZE_UNKNOWN,
    );
    (ZSTD_estimateDCtxSize())
        .wrapping_add(inBuffSize)
        .wrapping_add(outBuffSize)
}
#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_estimateDStreamSize_fromFrame))]
pub unsafe extern "C" fn ZSTD_estimateDStreamSize_fromFrame(
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    let windowSizeMax = (1)
        << (if ::core::mem::size_of::<size_t>() == 4 {
            ZSTD_WINDOWLOG_MAX_32
        } else {
            ZSTD_WINDOWLOG_MAX_64
        });
    let mut zfh = ZSTD_FrameHeader {
        frameContentSize: 0,
        windowSize: 0,
        blockSizeMax: 0,
        frameType: ZSTD_frame,
        headerSize: 0,
        dictID: 0,
        checksumFlag: 0,
        _reserved1: 0,
        _reserved2: 0,
    };
    let err = ZSTD_getFrameHeader(&mut zfh, src, srcSize);
    if ERR_isError(err) {
        return err;
    }
    if err > 0 {
        return Error::srcSize_wrong.to_error_code();
    }
    if zfh.windowSize > windowSizeMax as core::ffi::c_ulonglong {
        return Error::frameParameter_windowTooLarge.to_error_code();
    }
    ZSTD_estimateDStreamSize(zfh.windowSize as size_t)
}
unsafe fn ZSTD_DCtx_isOverflow(
    zds: *mut ZSTD_DStream,
    neededInBuffSize: size_t,
    neededOutBuffSize: size_t,
) -> core::ffi::c_int {
    (((*zds).inBuffSize).wrapping_add((*zds).outBuffSize)
        >= neededInBuffSize.wrapping_add(neededOutBuffSize)
            * ZSTD_WORKSPACETOOLARGE_FACTOR as size_t) as core::ffi::c_int
}
unsafe fn ZSTD_DCtx_updateOversizedDuration(
    zds: *mut ZSTD_DStream,
    neededInBuffSize: size_t,
    neededOutBuffSize: size_t,
) {
    if ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize) != 0 {
        (*zds).oversizedDuration = ((*zds).oversizedDuration).wrapping_add(1);
        (*zds).oversizedDuration;
    } else {
        (*zds).oversizedDuration = 0;
    };
}
unsafe fn ZSTD_DCtx_isOversizedTooLong(zds: *mut ZSTD_DStream) -> core::ffi::c_int {
    ((*zds).oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION as size_t) as core::ffi::c_int
}
unsafe fn ZSTD_checkOutBuffer(zds: *const ZSTD_DStream, output: *const ZSTD_outBuffer) -> size_t {
    if (*zds).outBufferMode != BufferMode::Stable {
        return 0;
    }
    if (*zds).streamStage == StreamStage::Init {
        return 0;
    }
    let expect = (*zds).expectedOutBuffer;
    if expect.dst == (*output).dst && expect.pos == (*output).pos && expect.size == (*output).size {
        return 0;
    }
    Error::dstBuffer_wrong.to_error_code()
}
unsafe fn ZSTD_decompressContinueStream(
    zds: *mut ZSTD_DStream,
    op: *mut *mut core::ffi::c_char,
    oend: *mut core::ffi::c_char,
    src: *const core::ffi::c_void,
    srcSize: size_t,
) -> size_t {
    let isSkipFrame = ZSTD_isSkipFrame(zds);
    if (*zds).outBufferMode == BufferMode::Buffered {
        let dstSize = if isSkipFrame != 0 {
            0
        } else {
            ((*zds).outBuffSize).wrapping_sub((*zds).outStart)
        };
        let decodedSize = ZSTD_decompressContinue(
            zds,
            ((*zds).outBuff).add((*zds).outStart) as *mut core::ffi::c_void,
            dstSize,
            src,
            srcSize,
        );
        let err_code = decodedSize;
        if ERR_isError(err_code) {
            return err_code;
        }
        if decodedSize == 0 && isSkipFrame == 0 {
            (*zds).streamStage = StreamStage::Read;
        } else {
            (*zds).outEnd = ((*zds).outStart).wrapping_add(decodedSize);
            (*zds).streamStage = StreamStage::Flush;
        }
    } else {
        let dstSize_0 = if isSkipFrame != 0 {
            0
        } else {
            oend.offset_from(*op) as size_t
        };
        let decodedSize_0 =
            ZSTD_decompressContinue(zds, *op as *mut core::ffi::c_void, dstSize_0, src, srcSize);
        let err_code_0 = decodedSize_0;
        if ERR_isError(err_code_0) {
            return err_code_0;
        }
        *op = (*op).add(decodedSize_0);
        (*zds).streamStage = StreamStage::Read;
    }
    0
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressStream))]
pub unsafe extern "C" fn ZSTD_decompressStream(
    zds: *mut ZSTD_DStream,
    output: *mut ZSTD_outBuffer,
    input: *mut ZSTD_inBuffer,
) -> size_t {
    let output = output.as_mut().unwrap();
    let input = input.as_mut().unwrap();

    let src = input.src as *const core::ffi::c_char;
    let istart = if input.pos != 0 {
        src.add(input.pos)
    } else {
        src
    };
    let iend = if input.size != 0 {
        src.add(input.size)
    } else {
        src
    };
    let mut ip = istart;
    let dst = output.dst as *mut core::ffi::c_char;
    let ostart = if output.pos != 0 {
        dst.add(output.pos)
    } else {
        dst
    };
    let oend = if output.size != 0 {
        dst.add(output.size)
    } else {
        dst
    };
    let mut op = ostart;
    let mut some_more_work = true;
    if input.pos > input.size {
        return Error::srcSize_wrong.to_error_code();
    }
    if output.pos > output.size {
        return Error::dstSize_tooSmall.to_error_code();
    }
    let err_code = ZSTD_checkOutBuffer(zds, output);
    if ERR_isError(err_code) {
        return err_code;
    }

    while some_more_work {
        #[derive(Eq, PartialEq)]
        enum Block {
            LoadHeader,
            Read,
            Load,
        }
        let mut current_block: Block;
        match (*zds).streamStage {
            StreamStage::Init => {
                (*zds).streamStage = StreamStage::LoadHeader;
                (*zds).outEnd = 0;
                (*zds).outStart = (*zds).outEnd;
                (*zds).inPos = (*zds).outStart;
                (*zds).lhSize = (*zds).inPos;
                (*zds).legacyVersion = 0;
                (*zds).hostageByte = 0;
                (*zds).expectedOutBuffer = *output;
                current_block = Block::LoadHeader;
            }
            StreamStage::LoadHeader => {
                current_block = Block::LoadHeader;
            }
            StreamStage::Read => {
                current_block = Block::Read;
            }
            StreamStage::Load => {
                current_block = Block::Load;
            }
            StreamStage::Flush => {
                let toFlushSize = ((*zds).outEnd).wrapping_sub((*zds).outStart);
                let flushedSize = ZSTD_limitCopy(
                    op as *mut core::ffi::c_void,
                    oend.offset_from(op) as size_t,
                    ((*zds).outBuff).add((*zds).outStart) as *const core::ffi::c_void,
                    toFlushSize,
                );

                op = if !op.is_null() {
                    op.add(flushedSize)
                } else {
                    op
                };

                (*zds).outStart = ((*zds).outStart).wrapping_add(flushedSize);
                if flushedSize == toFlushSize {
                    // flush completed
                    (*zds).streamStage = StreamStage::Read;
                    if ((*zds).outBuffSize as core::ffi::c_ulonglong)
                        < (*zds).fParams.frameContentSize
                        && ((*zds).outStart).wrapping_add((*zds).fParams.blockSizeMax as size_t)
                            > (*zds).outBuffSize
                    {
                        (*zds).outEnd = 0;
                        (*zds).outStart = 0;
                    }
                    continue;
                }

                // cannot complete flush
                some_more_work = false;
                continue;
            }
        }
        if current_block == Block::LoadHeader {
            drop(current_block);

            if (*zds).legacyVersion != 0 {
                if (*zds).staticSize != 0 {
                    return Error::memory_allocation.to_error_code();
                }
                let hint = ZSTD_decompressLegacyStream(
                    (*zds).legacyContext,
                    (*zds).legacyVersion,
                    output,
                    input,
                );
                if hint == 0 {
                    (*zds).streamStage = StreamStage::Init;
                }
                return hint;
            }

            let hSize = get_frame_header_advanced(
                &mut (*zds).fParams,
                &(&(*zds).headerBuffer)[..(*zds).lhSize],
                (*zds).format,
            );
            if (*zds).refMultipleDDicts != MultipleDDicts::Single && !(*zds).ddictSet.is_null() {
                ZSTD_DCtx_selectFrameDDict(zds);
            }
            if ERR_isError(hSize) {
                let legacyVersion = ZSTD_isLegacy(
                    istart as *const core::ffi::c_void,
                    iend.offset_from(istart) as size_t,
                );
                if legacyVersion != 0 {
                    let ddict = ZSTD_getDDict(zds);
                    let dict = if !ddict.is_null() {
                        ZSTD_DDict_dictContent(ddict)
                    } else {
                        core::ptr::null()
                    };
                    let dictSize = if !ddict.is_null() {
                        ZSTD_DDict_dictSize(ddict)
                    } else {
                        0
                    };
                    if (*zds).staticSize != 0 {
                        return Error::memory_allocation.to_error_code();
                    }
                    let err_code = ZSTD_initLegacyStream(
                        &mut (*zds).legacyContext,
                        (*zds).previousLegacyVersion,
                        legacyVersion,
                        dict,
                        dictSize,
                    );
                    if ERR_isError(err_code) {
                        return err_code;
                    }
                    (*zds).previousLegacyVersion = legacyVersion;
                    (*zds).legacyVersion = (*zds).previousLegacyVersion;
                    let hint = ZSTD_decompressLegacyStream(
                        (*zds).legacyContext,
                        legacyVersion,
                        output,
                        input,
                    );
                    if hint == 0 {
                        (*zds).streamStage = StreamStage::Init;
                    }
                    return hint;
                }

                // error
                return hSize;
            }

            if hSize != 0 {
                // need more input
                let toLoad = hSize - (*zds).lhSize; // if hSize!=0, hSize > zds->lhSize
                let remainingInput = iend.offset_from(ip) as size_t;
                if toLoad > remainingInput {
                    // not enough input to load full header
                    if remainingInput > 0 {
                        libc::memcpy(
                            ((*zds).headerBuffer).as_mut_ptr().add((*zds).lhSize)
                                as *mut core::ffi::c_void,
                            ip as *const core::ffi::c_void,
                            remainingInput as libc::size_t,
                        );
                        (*zds).lhSize = ((*zds).lhSize).wrapping_add(remainingInput);
                    }
                    input.pos = input.size;
                    // check first few bytes
                    let err_code = get_frame_header_advanced(
                        &mut (*zds).fParams,
                        &(&(*zds).headerBuffer)[..(*zds).lhSize],
                        (*zds).format,
                    );
                    if ERR_isError(err_code) {
                        return err_code;
                    }
                    // remaining header bytes + next block header
                    return std::cmp::max(ZSTD_FRAMEHEADERSIZE_MIN((*zds).format), hSize)
                        .wrapping_sub((*zds).lhSize)
                        .wrapping_add(ZSTD_blockHeaderSize);
                }
                assert!(!ip.is_null());
                libc::memcpy(
                    ((*zds).headerBuffer).as_mut_ptr().add((*zds).lhSize) as *mut core::ffi::c_void,
                    ip as *const core::ffi::c_void,
                    toLoad as libc::size_t,
                );
                (*zds).lhSize = hSize;
                ip = ip.add(toLoad);
                continue;
            } else {
                // check for single-pass mode opportunity
                if (*zds).fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
                    && (*zds).fParams.frameType != ZSTD_skippableFrame
                    && oend.offset_from(op) as size_t as core::ffi::c_ulonglong
                        >= (*zds).fParams.frameContentSize
                {
                    let cSize = ZSTD_findFrameCompressedSize_advanced(
                        core::slice::from_raw_parts(
                            istart.cast(),
                            iend.offset_from(istart) as usize,
                        ),
                        (*zds).format,
                    );
                    if cSize <= iend.offset_from(istart) as size_t {
                        let decompressedSize = ZSTD_decompress_usingDDict(
                            zds,
                            op as *mut core::ffi::c_void,
                            oend.offset_from(op) as size_t,
                            istart as *const core::ffi::c_void,
                            cSize,
                            ZSTD_getDDict(zds),
                        );
                        if ERR_isError(decompressedSize) {
                            return decompressedSize;
                        }
                        assert!(!istart.is_null());
                        ip = istart.add(cSize);
                        op = if !op.is_null() {
                            op.add(decompressedSize)
                        } else {
                            // can occur if frameContentSize = 0 (empty frame)
                            op
                        };
                        (*zds).expected = 0;
                        (*zds).streamStage = StreamStage::Init;
                        some_more_work = false;
                        continue;
                    }
                }

                // Check output buffer is large enough for ZSTD_odm_stable.
                if (*zds).outBufferMode == BufferMode::Stable
                    && (*zds).fParams.frameType != ZSTD_skippableFrame
                    && (*zds).fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
                    && (oend.offset_from(op) as size_t as core::ffi::c_ulonglong)
                        < (*zds).fParams.frameContentSize
                {
                    return Error::dstSize_tooSmall.to_error_code();
                }
                let err_code = ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds));
                if ERR_isError(err_code) {
                    return err_code;
                }
                if (*zds).format == Format::ZSTD_f_zstd1
                    && MEM_readLE32(((*zds).headerBuffer).as_mut_ptr() as *const core::ffi::c_void)
                        & ZSTD_MAGIC_SKIPPABLE_MASK
                        == ZSTD_MAGIC_SKIPPABLE_START as core::ffi::c_uint
                {
                    // skippable frame
                    (*zds).expected =
                        MEM_readLE32(((*zds).headerBuffer).as_mut_ptr().add(ZSTD_FRAMEIDSIZE)
                            as *const core::ffi::c_void) as size_t;
                    (*zds).stage = DecompressStage::SkipFrame;
                } else {
                    let err_code =
                        ZSTD_decodeFrameHeader(zds, &((&(*zds).headerBuffer)[..(*zds).lhSize]));
                    if ERR_isError(err_code) {
                        return err_code;
                    }
                    (*zds).expected = ZSTD_blockHeaderSize;
                    (*zds).stage = DecompressStage::DecodeBlockHeader;
                }

                // control buffer memory usage
                (*zds).fParams.windowSize = std::cmp::min(
                    (*zds).fParams.windowSize,
                    (1 << ZSTD_WINDOWLOG_ABSOLUTEMIN) as core::ffi::c_ulonglong,
                );
                if (*zds).fParams.windowSize > (*zds).maxWindowSize as core::ffi::c_ulonglong {
                    return Error::frameParameter_windowTooLarge.to_error_code();
                }
                if (*zds).maxBlockSizeParam != 0 {
                    (*zds).fParams.blockSizeMax = std::cmp::min(
                        (*zds).fParams.blockSizeMax,
                        (*zds).maxBlockSizeParam as core::ffi::c_uint,
                    );
                }

                // Adapt buffer sizes to frame header instructions
                let neededInBuffSize = std::cmp::max((*zds).fParams.blockSizeMax, 4) as size_t;
                let neededOutBuffSize = if (*zds).outBufferMode == BufferMode::Buffered {
                    ZSTD_decodingBufferSize_internal(
                        (*zds).fParams.windowSize,
                        (*zds).fParams.frameContentSize,
                        (*zds).fParams.blockSizeMax as size_t,
                    )
                } else {
                    0
                };

                ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize);

                let tooSmall = ((*zds).inBuffSize < neededInBuffSize
                    || (*zds).outBuffSize < neededOutBuffSize)
                    as core::ffi::c_int;
                let tooLarge = ZSTD_DCtx_isOversizedTooLong(zds);

                if tooSmall != 0 || tooLarge != 0 {
                    let bufferSize = neededInBuffSize.wrapping_add(neededOutBuffSize);
                    if (*zds).staticSize != 0 {
                        // static DCtx
                        assert!((*zds).staticSize >= size_of::<ZSTD_DCtx>()); // controlled at init
                        if bufferSize > (*zds).staticSize - size_of::<ZSTD_DCtx>() {
                            return Error::dictionary_corrupted.to_error_code();
                        }
                    } else {
                        ZSTD_customFree((*zds).inBuff as *mut core::ffi::c_void, (*zds).customMem);
                        (*zds).inBuffSize = 0;
                        (*zds).outBuffSize = 0;
                        (*zds).inBuff = ZSTD_customMalloc(bufferSize, (*zds).customMem)
                            as *mut core::ffi::c_char;
                        if (*zds).inBuff.is_null() {
                            return Error::dictionary_corrupted.to_error_code();
                        }
                    }
                    (*zds).inBuffSize = neededInBuffSize;
                    (*zds).outBuff = ((*zds).inBuff).add((*zds).inBuffSize);
                    (*zds).outBuffSize = neededOutBuffSize;
                }
                (*zds).streamStage = StreamStage::Read;
                current_block = Block::Read;
            }
        }

        if current_block == Block::Read {
            drop(current_block);

            let neededInSize =
                ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend.offset_from(ip) as size_t);
            if neededInSize == 0 {
                (*zds).streamStage = StreamStage::Init;
                some_more_work = false;
                continue;
            } else if iend.offset_from(ip) as size_t >= neededInSize {
                // decode directly from src
                let err_code_4 = ZSTD_decompressContinueStream(
                    zds,
                    &mut op,
                    oend,
                    ip as *const core::ffi::c_void,
                    neededInSize,
                );
                if ERR_isError(err_code_4) {
                    return err_code_4;
                }
                assert!(!ip.is_null());
                ip = ip.add(neededInSize);
                // Function modifies the stage so we must break
                continue;
            } else if ip == iend {
                // no more input
                some_more_work = false;
                continue;
            } else {
                (*zds).streamStage = StreamStage::Load;
                current_block = Block::Load;
            }
        }

        if current_block == Block::Load {
            drop(current_block);

            let neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
            let toLoad_0 = neededInSize.wrapping_sub((*zds).inPos);
            let isSkipFrame = ZSTD_isSkipFrame(zds);
            let mut loadedSize: size_t = 0;
            // At this point we shouldn't be decompressing a block that we can stream.
            assert!(
                neededInSize
                    == ZSTD_nextSrcSizeToDecompressWithInputSize(
                        zds,
                        iend.offset_from(ip) as usize
                    )
            );
            if isSkipFrame != 0 {
                loadedSize = std::cmp::min(toLoad_0, iend.offset_from(ip) as size_t);
            } else {
                if toLoad_0 > ((*zds).inBuffSize).wrapping_sub((*zds).inPos) {
                    return Error::corruption_detected.to_error_code();
                }
                loadedSize = ZSTD_limitCopy(
                    ((*zds).inBuff).add((*zds).inPos) as *mut core::ffi::c_void,
                    toLoad_0,
                    ip as *const core::ffi::c_void,
                    iend.offset_from(ip) as size_t,
                );
            }
            if loadedSize != 0 {
                // ip may be NULL
                ip = ip.add(loadedSize);
                (*zds).inPos = ((*zds).inPos).wrapping_add(loadedSize);
            }
            if loadedSize < toLoad_0 {
                // not enough input, wait for more
                some_more_work = false;
            } else {
                // decode loaded input
                (*zds).inPos = 0; // input is consumed
                let err_code_5 = ZSTD_decompressContinueStream(
                    zds,
                    &mut op,
                    oend,
                    (*zds).inBuff as *const core::ffi::c_void,
                    neededInSize,
                );
                if ERR_isError(err_code_5) {
                    return err_code_5;
                }
                // Function modifies the stage so we must break
            }
        }
    }

    // result
    input.pos = ip.offset_from(input.src as *const core::ffi::c_char) as size_t;
    output.pos = op.offset_from(output.dst as *mut core::ffi::c_char) as size_t;

    // Update the expected output buffer for ZSTD_obm_stable.
    (*zds).expectedOutBuffer = *output;

    if ip == istart && op == ostart {
        // no forward progress
        (*zds).noForwardProgress += 1;
        (*zds).noForwardProgress;
        if (*zds).noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX {
            if op == oend {
                return Error::noForwardProgress_destFull.to_error_code();
            }
            if ip == iend {
                return Error::noForwardProgress_inputEmpty.to_error_code();
            }
            unreachable!();
        }
    } else {
        (*zds).noForwardProgress = 0;
    }

    let mut nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
    if nextSrcSizeHint == 0 {
        // frame fully decoded
        if (*zds).outEnd == (*zds).outStart {
            // output fully flushed
            if (*zds).hostageByte != 0 {
                if input.pos >= input.size {
                    // can't release hostage (not present)
                    (*zds).streamStage = StreamStage::Read;
                    return 1;
                }
                // release hostage
                input.pos = (input.pos).wrapping_add(1);
            }
            return 0;
        }
        if (*zds).hostageByte == 0 {
            // output not fully flushed; keep last byte as hostage; will be
            // released when all output is flushed
            // note : pos > 0, otherwise, impossible to finish reading last block
            input.pos = (input.pos).wrapping_sub(1);
            (*zds).hostageByte = 1;
        }
        return 1;
    }
    // preload header of next block
    nextSrcSizeHint = nextSrcSizeHint.wrapping_add(
        ZSTD_blockHeaderSize
            * ((*zds).stage.to_next_input_type() == NextInputType::Block) as size_t,
    );
    assert!((*zds).inPos <= nextSrcSizeHint);
    // part already loaded
    nextSrcSizeHint = nextSrcSizeHint.wrapping_sub((*zds).inPos);
    nextSrcSizeHint
}

#[cfg_attr(feature = "export-symbols", export_name = crate::prefix!(ZSTD_decompressStream_simpleArgs))]
pub unsafe extern "C" fn ZSTD_decompressStream_simpleArgs(
    dctx: *mut ZSTD_DCtx,
    dst: *mut core::ffi::c_void,
    dstCapacity: size_t,
    dstPos: *mut size_t,
    src: *const core::ffi::c_void,
    srcSize: size_t,
    srcPos: *mut size_t,
) -> size_t {
    let mut output = ZSTD_outBuffer_s {
        dst: core::ptr::null_mut::<core::ffi::c_void>(),
        size: 0,
        pos: 0,
    };
    let mut input = ZSTD_inBuffer_s {
        src: core::ptr::null::<core::ffi::c_void>(),
        size: 0,
        pos: 0,
    };
    output.dst = dst;
    output.size = dstCapacity;
    output.pos = *dstPos;
    input.src = src;
    input.size = srcSize;
    input.pos = *srcPos;
    let cErr = ZSTD_decompressStream(dctx, &mut output, &mut input);
    *dstPos = output.pos;
    *srcPos = input.pos;
    cErr
}

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

    #[test]
    fn decompress_bound_null() {
        assert_eq!(unsafe { ZSTD_decompressBound(core::ptr::null(), 0) }, 0);
    }

    quickcheck! {
        #[cfg(not(miri))]
        fn decompress_bound_quickcheck(input: Vec<u8>) -> bool {
            unsafe {
                let expected = zstd_sys::ZSTD_decompressBound(input.as_ptr().cast(), input.len() );
                let actual = super::ZSTD_decompressBound(input.as_ptr().cast(), input.len());

                assert_eq!(expected, actual);
                expected == actual
            }
        }
    }

    #[test]
    fn decompression_margin_null() {
        assert_eq!(unsafe { ZSTD_decompressionMargin(core::ptr::null(), 0) }, 0);
    }

    quickcheck! {
        #[cfg(not(miri))]
        fn decompression_margin_quickcheck(input: Vec<u8>) -> bool {
            unsafe {
                let expected = zstd_sys::ZSTD_decompressionMargin(input.as_ptr().cast(), input.len() );
                let actual = super::ZSTD_decompressionMargin(input.as_ptr().cast(), input.len());

                assert_eq!(expected, actual);
                expected == actual
            }
        }
    }
}