structured-zstd 0.2.5

Pure-Rust Zstandard (zstd) compression and decompression: all levels, streaming, dictionaries, no_std and WebAssembly ready — no FFI, no cmake
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
//! Frames written by the v0.5, v0.6 and v0.7 release command lines
//! (`scripts/legacy-fixtures.sh`) decode to the files they were made from.

use super::*;
use alloc::vec;
use alloc::vec::Vec;

#[cfg(feature = "std")]
mod fixtures {
    use super::*;
    use alloc::format;
    use alloc::string::{String, ToString};
    use std::path::{Path, PathBuf};

    pub(super) struct Fixture {
        pub(super) name: String,
        pub(super) frame: Vec<u8>,
        pub(super) content: Vec<u8>,
        pub(super) dict: Option<Vec<u8>>,
        /// `dict` as the dictionary parser reads it.
        pub(super) parsed: Option<crate::decoding::Dictionary>,
        pub(super) version: LegacyVersion,
    }

    impl Fixture {
        /// The fixture's dictionary as the decoders take it.
        pub(super) fn legacy_dict(&self) -> LegacyDict<'_> {
            self.parsed
                .as_ref()
                .map_or(LegacyDict::None, |dict| LegacyDict::Parsed {
                    dict,
                    header: &[],
                })
        }
    }

    fn root() -> &'static Path {
        Path::new(env!("CARGO_MANIFEST_DIR"))
    }

    /// Every fixture, with the file it decodes to and the dictionary it needs.
    pub(super) fn all() -> Vec<Fixture> {
        let dir = root().join("legacy_frames");
        let mut names: Vec<String> = std::fs::read_dir(&dir)
            .expect("legacy_frames directory")
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .filter(|name| name.ends_with(".zst"))
            .collect();
        names.sort();
        assert!(names.len() >= 50, "fixtures missing from {}", dir.display());
        names
            .into_iter()
            .map(|name| {
                let (stem, rest) = ["v05", "v06", "v07"]
                    .iter()
                    .find_map(|tag| {
                        name.split_once(&format!(".{tag}."))
                            .map(|split| (split, *tag))
                    })
                    .map(|((stem, _), tag)| (stem.to_string(), tag))
                    .expect("fixture name carries its version");
                let version = match rest {
                    "v05" => LegacyVersion::V05,
                    "v06" => LegacyVersion::V06,
                    _ => LegacyVersion::V07,
                };
                let is_dict = name.contains(".dict");
                // `<file>x<N>` is the file N times over.
                let (file, times) = stem
                    .rsplit_once('x')
                    .and_then(|(file, n)| Some((file, n.parse::<usize>().ok()?)))
                    .unwrap_or((stem.as_str(), 1));
                let source: PathBuf = if is_dict {
                    root().join("dict_tests/files").join(file)
                } else {
                    root().join("decodecorpus_files").join(file)
                };
                let dict =
                    is_dict.then(|| std::fs::read(dir.join(format!("dictionary.{rest}"))).unwrap());
                Fixture {
                    frame: std::fs::read(dir.join(&name)).unwrap(),
                    content: std::fs::read(&source).unwrap().repeat(times),
                    parsed: dict.as_deref().map(|raw| {
                        crate::decoding::Dictionary::from_serialized_or_raw_content(raw).unwrap()
                    }),
                    dict,
                    version,
                    name,
                }
            })
            .collect()
    }
}

#[cfg(feature = "std")]
use fixtures::all as fixtures;

fn decode_to_vec(frame: &[u8], dict: LegacyDict<'_>) -> Result<(Vec<u8>, usize), Error> {
    decode_to_vec_in(
        frame,
        dict,
        FrameOptions::default(),
        &mut Workspace::default(),
    )
}

/// [`decode_to_vec`] refusing a frame whose content checksum does not match.
fn decode_verified(frame: &[u8], dict: LegacyDict<'_>) -> Result<(Vec<u8>, usize), Error> {
    let options = FrameOptions {
        #[cfg(feature = "hash")]
        checksum: crate::decoding::ContentChecksum::Verify,
        ..FrameOptions::default()
    };
    decode_to_vec_in(frame, dict, options, &mut Workspace::default())
}

/// [`decode_to_vec`] with `options`, in `workspace`, the storage an earlier
/// frame left.
fn decode_to_vec_in(
    frame: &[u8],
    dict: LegacyDict<'_>,
    options: FrameOptions,
    workspace: &mut Workspace,
) -> Result<(Vec<u8>, usize), Error> {
    let mut buf = Vec::new();
    let mut out = VecOutput {
        buf: &mut buf,
        start: 0,
    };
    let (consumed, _) = decode_frame(frame, dict, options, workspace, &mut out)?;
    Ok((buf, consumed))
}

/// Each fixture names its own format and decodes byte-exact, taking exactly
/// its own bytes: in a fresh decoder, and in one every fixture before it
/// left its tables in, whatever its format and dictionary.
#[cfg(feature = "std")]
#[test]
fn fixtures_decode_to_their_content() {
    let mut reused = Workspace::default();
    for fixture in fixtures() {
        assert_eq!(
            LegacyVersion::of(&fixture.frame),
            Some(fixture.version),
            "{}",
            fixture.name
        );
        for workspace in [&mut Workspace::default(), &mut reused] {
            let (decoded, consumed) = decode_to_vec_in(
                &fixture.frame,
                fixture.legacy_dict(),
                FrameOptions::default(),
                workspace,
            )
            .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
            assert_eq!(consumed, fixture.frame.len(), "{}", fixture.name);
            assert!(
                decoded == fixture.content,
                "{} decodes to other bytes",
                fixture.name
            );
        }
    }
}

/// Decoding into a caller's slice gives the same bytes, and a slice one byte
/// short is refused as too small rather than written past.
#[cfg(feature = "std")]
#[test]
fn fixtures_decode_into_a_slice() {
    for fixture in fixtures() {
        let dict = fixture.legacy_dict();
        let mut buf = vec![0u8; fixture.content.len()];
        let mut out = SliceOutput {
            buf: &mut buf,
            pos: 0,
        };
        decode_frame(
            &fixture.frame,
            dict,
            FrameOptions::default(),
            &mut Workspace::default(),
            &mut out,
        )
        .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
        assert_eq!(out.pos, fixture.content.len(), "{}", fixture.name);
        assert!(buf == fixture.content, "{}", fixture.name);

        if let Some(short) = fixture.content.len().checked_sub(1) {
            let mut buf = vec![0u8; short];
            let mut out = SliceOutput {
                buf: &mut buf,
                pos: 0,
            };
            assert!(
                matches!(
                    decode_frame(
                        &fixture.frame,
                        dict,
                        FrameOptions::default(),
                        &mut Workspace::default(),
                        &mut out
                    ),
                    Err(Error::OutputTooSmall)
                ),
                "{}",
                fixture.name
            );
        }
    }
}

/// The size walk ends where the decoder does, and bounds the content by its
/// blocks.
#[cfg(feature = "std")]
#[test]
fn frame_size_matches_the_decoded_frame() {
    for fixture in fixtures() {
        let (size, bound) = frame_size(fixture.version, &fixture.frame).unwrap();
        assert_eq!(size, fixture.frame.len(), "{}", fixture.name);
        assert!(bound >= fixture.content.len() as u64, "{}", fixture.name);
    }
}

/// A v0.7 frame naming a dictionary by ID is refused without it, and with a
/// dictionary of another ID, saying which it needs. (v0.5 and v0.6 frames
/// carry no ID; one whose blocks never reach into the dictionary decodes
/// without it.)
#[cfg(feature = "std")]
#[test]
fn a_v07_frame_naming_a_dictionary_needs_it() {
    for fixture in fixtures()
        .into_iter()
        .filter(|f| f.name.ends_with(".v07.dict.zst"))
    {
        assert_eq!(
            decode_to_vec(&fixture.frame, LegacyDict::None).unwrap_err(),
            Error::DictionaryMismatch {
                expected: 7,
                provided: 0
            },
            "{}",
            fixture.name
        );
        let mut other = fixture.dict.clone().unwrap();
        other[4] ^= 1;
        let other = crate::decoding::Dictionary::decode_dict(&other).unwrap();
        assert_eq!(
            decode_to_vec(
                &fixture.frame,
                LegacyDict::Parsed {
                    dict: &other,
                    header: &[]
                }
            )
            .unwrap_err(),
            Error::DictionaryMismatch {
                expected: 7,
                provided: 6
            },
            "{}",
            fixture.name
        );
    }
}

/// A v0.7 dictionary read by the RFC 8878 parser primes the decoder as its
/// raw bytes do, and a raw-content one gives its content and its ID.
#[cfg(feature = "std")]
#[test]
fn a_parsed_dictionary_decodes_like_its_bytes() {
    for fixture in fixtures().into_iter().filter(|f| f.dict.is_some()) {
        let raw = fixture.dict.as_deref().unwrap();
        let parsed = crate::decoding::Dictionary::from_serialized_or_raw_content(raw).unwrap();
        let dict = LegacyDict::Parsed {
            dict: &parsed,
            header: &[],
        };
        let (decoded, _) = decode_to_vec(&fixture.frame, dict)
            .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
        assert!(decoded == fixture.content, "{}", fixture.name);
    }
    // A raw-content dictionary answers to the ID it was given.
    let fixture = fixtures()
        .into_iter()
        .find(|f| f.name.ends_with(".v07.dict.zst"))
        .unwrap();
    let raw = crate::decoding::Dictionary::from_raw_content(6, vec![0; 64]).unwrap();
    assert_eq!(
        decode_to_vec(
            &fixture.frame,
            LegacyDict::Parsed {
                dict: &raw,
                header: &[]
            }
        )
        .unwrap_err(),
        Error::DictionaryMismatch {
            expected: 7,
            provided: 6
        }
    );
}

/// `FrameDecoder::decode_all` decodes each fixture, its dictionary given as a
/// handle or registered under the ID a v0.7 frame names, and a frame between
/// RFC 8878 frames; a slice one byte short is too small.
#[cfg(feature = "std")]
#[test]
fn decode_all_decodes_the_fixtures() {
    use crate::decoding::{DictionaryHandle, FrameDecoder, errors::FrameDecoderError};
    for fixture in fixtures() {
        let mut out = vec![0u8; fixture.content.len()];
        let mut decoder = FrameDecoder::new();
        let written = match &fixture.dict {
            None => decoder.decode_all(&fixture.frame, &mut out),
            Some(raw) => {
                let dict = DictionaryHandle::from_serialized_or_raw_content(raw).unwrap();
                decoder.decode_all_with_dict_handle(&fixture.frame, &mut out, &dict)
            }
        }
        .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
        assert_eq!(written, fixture.content.len(), "{}", fixture.name);
        assert!(out == fixture.content, "{}", fixture.name);
        if let Some(short) = fixture.content.len().checked_sub(1)
            && fixture.dict.is_none()
        {
            assert!(matches!(
                FrameDecoder::new().decode_all(&fixture.frame, &mut out[..short]),
                Err(FrameDecoderError::TargetTooSmall)
            ));
        }
    }

    let fixture = fixtures()
        .into_iter()
        .find(|f| f.name.ends_with(".v07.dict.zst"))
        .unwrap();
    let mut out = vec![0u8; fixture.content.len()];
    assert!(matches!(
        FrameDecoder::new().decode_all(&fixture.frame, &mut out),
        Err(FrameDecoderError::DictNotProvided { dict_id: 7 })
    ));
    let mut decoder = FrameDecoder::new();
    decoder
        .add_dict_from_bytes(fixture.dict.as_deref().unwrap())
        .unwrap();
    decoder.decode_all(&fixture.frame, &mut out).unwrap();
    assert!(out == fixture.content);

    let fixture = fixtures()
        .into_iter()
        .find(|f| f.name == "abc.txt.v06.l1.zst")
        .unwrap();
    let rfc = crate::encoding::compress_to_vec(
        &b"between"[..],
        crate::encoding::CompressionLevel::Fastest,
    );
    let mut input = rfc.clone();
    input.extend_from_slice(&fixture.frame);
    input.extend_from_slice(&rfc);
    let mut expected = b"between".to_vec();
    expected.extend_from_slice(&fixture.content);
    expected.extend_from_slice(b"between");
    let mut out = vec![0u8; expected.len()];
    assert_eq!(
        FrameDecoder::new().decode_all(&input, &mut out).unwrap(),
        expected.len()
    );
    assert!(out == expected);
}

/// A source that hands out one byte per read.
#[cfg(feature = "std")]
struct Trickle<'a>(&'a [u8]);

#[cfg(feature = "std")]
impl std::io::Read for Trickle<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let Some((&first, rest)) = self.0.split_first() else {
            return Ok(0);
        };
        if buf.is_empty() {
            return Ok(0);
        }
        buf[0] = first;
        self.0 = rest;
        Ok(1)
    }
}

/// `StreamingDecoder` decodes each fixture whole, and from a source that
/// gives one byte at a time into a small buffer, which drives the stream a
/// step at a time and keeps only a window of history; a stream mixing these
/// frames with RFC 8878 ones decodes in order.
#[cfg(feature = "std")]
#[test]
fn streaming_decoder_decodes_the_fixtures() {
    use crate::decoding::{DictionaryHandle, StreamingDecoder};
    use std::io::Read;
    for fixture in fixtures() {
        let dict = fixture
            .dict
            .as_deref()
            .map(|raw| DictionaryHandle::from_serialized_or_raw_content(raw).unwrap());
        let open = |source| match &dict {
            None => StreamingDecoder::new(source),
            Some(dict) => StreamingDecoder::new_with_dictionary_handle(source, dict).unwrap(),
        };
        let mut whole = Vec::new();
        open(&fixture.frame[..])
            .read_to_end(&mut whole)
            .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
        assert!(whole == fixture.content, "{}", fixture.name);

        if fixture.frame.len() < 64 * 1024 {
            let mut decoder = match &dict {
                None => StreamingDecoder::new(Trickle(&fixture.frame)),
                Some(dict) => {
                    StreamingDecoder::new_with_dictionary_handle(Trickle(&fixture.frame), dict)
                        .unwrap()
                }
            };
            let mut pieces = Vec::new();
            let mut buf = [0u8; 1000];
            loop {
                let n = decoder
                    .read(&mut buf)
                    .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
                if n == 0 {
                    break;
                }
                pieces.extend_from_slice(&buf[..n]);
            }
            assert!(pieces == fixture.content, "{} in pieces", fixture.name);
        }
    }

    let fixture = fixtures()
        .into_iter()
        .find(|f| f.name == "z000001.v07.l19.zst")
        .unwrap();
    let rfc = crate::encoding::compress_to_vec(
        &b"between"[..],
        crate::encoding::CompressionLevel::Fastest,
    );
    let mut input = rfc.clone();
    input.extend_from_slice(&fixture.frame);
    input.extend_from_slice(&rfc);
    input.extend_from_slice(&fixture.frame);
    let mut expected = b"between".to_vec();
    expected.extend_from_slice(&fixture.content);
    expected.extend_from_slice(b"between");
    expected.extend_from_slice(&fixture.content);
    let mut out = Vec::new();
    StreamingDecoder::new(&input[..])
        .read_to_end(&mut out)
        .unwrap();
    assert!(out == expected);
    let mut out = Vec::new();
    let mut decoder = StreamingDecoder::new(&input[..]);
    let mut buf = [0u8; 4096];
    loop {
        let n = decoder.read(&mut buf).unwrap();
        if n == 0 {
            break;
        }
        out.extend_from_slice(&buf[..n]);
    }
    assert!(out == expected);
}

/// The block-level interface drives these frames too: `reset` starts one,
/// `decode_blocks` decodes it a block at a time and `collect` hands it out;
/// `decode_from_to` decodes it from input given in small pieces.
#[cfg(feature = "std")]
#[test]
fn frame_decoder_steps_through_the_fixtures() {
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    for fixture in fixtures().into_iter().filter(|f| f.dict.is_none()) {
        let mut source = &fixture.frame[..];
        let mut decoder = FrameDecoder::new();
        decoder.reset(&mut source).unwrap();
        let mut out = Vec::new();
        while !decoder
            .decode_blocks(&mut source, BlockDecodingStrategy::UptoBlocks(1))
            .unwrap_or_else(|err| panic!("{}: {err}", fixture.name))
        {
            out.extend(decoder.collect().unwrap());
        }
        out.extend(decoder.collect().unwrap());
        assert!(source.is_empty(), "{}", fixture.name);
        assert!(out == fixture.content, "{}", fixture.name);
        assert_eq!(
            decoder.bytes_read_from_source(),
            fixture.frame.len() as u64,
            "{}",
            fixture.name
        );

        // `decode_from_to` with what the decoder asks for, and a target
        // smaller than a block.
        let mut decoder = FrameDecoder::new();
        let mut source = &fixture.frame[..];
        decoder.reset(&mut source).unwrap();
        let mut out = Vec::new();
        let mut target = [0u8; 777];
        while !(decoder.is_finished() && decoder.can_collect() == 0) {
            let need = decoder.input_needed(source).min(source.len());
            let (read, written) = decoder
                .decode_from_to(&source[..need], &mut target)
                .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
            source = &source[read..];
            out.extend_from_slice(&target[..written]);
            assert!(read > 0 || written > 0, "{} stalled", fixture.name);
        }
        assert!(out == fixture.content, "{}", fixture.name);
    }
}

/// The frame queries answer for these frames as libzstd does: a frame, its
/// length through the end block, its declared size or unknown, and a bound
/// of 128 KiB per block; a cut frame is truncated.
#[cfg(feature = "std")]
#[test]
fn frame_queries_answer_for_the_fixtures() {
    use crate::decoding::{
        FrameContentSize, FrameSizeError, find_decompressed_size, find_frame_compressed_size,
        frame_decompressed_bound, is_frame, read_frame_content_size,
    };
    for fixture in fixtures() {
        let frame = &fixture.frame;
        assert!(is_frame(frame), "{}", fixture.name);
        assert_eq!(
            find_frame_compressed_size(frame).unwrap(),
            frame.len(),
            "{}",
            fixture.name
        );
        let bound = frame_decompressed_bound(frame).unwrap();
        assert!(bound >= fixture.content.len() as u64, "{}", fixture.name);
        let declared = declared_content_size(frame);
        let expected = declared.map_or(FrameContentSize::Unknown, FrameContentSize::Known);
        assert_eq!(
            read_frame_content_size(frame).unwrap(),
            expected,
            "{}",
            fixture.name
        );
        assert_eq!(
            find_decompressed_size(frame).unwrap(),
            expected,
            "{}",
            fixture.name
        );
        assert!(matches!(
            find_frame_compressed_size(&frame[..frame.len() - 1]),
            Err(FrameSizeError::Truncated)
        ));
    }
    // v0.5 declares no size.
    let v05 = fixtures()
        .into_iter()
        .find(|f| f.name == "abc.txt.v05.l1.zst")
        .unwrap();
    assert_eq!(
        read_frame_content_size(&v05.frame).unwrap(),
        FrameContentSize::Unknown
    );
}

/// Every truncation of every fixture is refused or decodes to a prefix, and
/// none panics.
#[cfg(feature = "std")]
#[test]
fn truncated_frames_are_refused() {
    for fixture in fixtures().into_iter().filter(|f| f.frame.len() < 4096) {
        let dict = fixture.legacy_dict();
        for len in 0..fixture.frame.len() {
            assert!(
                decode_to_vec(&fixture.frame[..len], dict).is_err(),
                "{} cut to {len} bytes decoded",
                fixture.name
            );
        }
    }
}

/// Flipping any one bit of a frame is refused or decodes to some output, but
/// never panics; a v0.7 frame with a checksum, verified, decodes to other
/// content only when that content's checksum is the one the frame carries,
/// which with 22 bits of it does happen.
#[cfg(feature = "std")]
#[test]
fn damaged_frames_never_panic() {
    for fixture in fixtures().into_iter().filter(|f| f.frame.len() < 4096) {
        let dict = fixture.legacy_dict();
        let mut frame = fixture.frame.clone();
        for byte in 0..frame.len() {
            for bit in 0..8 {
                frame[byte] ^= 1 << bit;
                let decoded = decode_verified(&frame, dict);
                #[cfg(feature = "hash")]
                if let Ok((content, end)) = &decoded
                    && *content != fixture.content
                    && read_header(&frame).is_ok_and(|header| header.checksum)
                {
                    let carried = u64::from(frame[end - 1])
                        | u64::from(frame[end - 2]) << 8
                        | u64::from(frame[end - 3] & 0x3F) << 16;
                    let digest = twox_hash::XxHash64::oneshot(0, content) >> 11 & 0x3F_FFFF;
                    assert_eq!(
                        digest, carried,
                        "{}: bit {bit} of byte {byte} changed the content unchecked",
                        fixture.name
                    );
                }
                drop(decoded);
                frame[byte] ^= 1 << bit;
            }
        }
    }
}

/// A v0.7 frame whose content checksum does not match is refused with the
/// checksum error when verified, and decodes when not.
#[cfg(all(feature = "std", feature = "hash"))]
#[test]
fn a_wrong_v07_checksum_is_refused() {
    let fixture = fixture("abc.txt.v07.l1.zst");
    let mut frame = fixture.frame.clone();
    // The end block's header holds the checksum in its low 22 bits.
    let last = frame.len() - 1;
    frame[last] ^= 1;
    assert!(matches!(
        decode_verified(&frame, LegacyDict::None),
        Err(Error::ChecksumMismatch { .. })
    ));
    assert!(decode_to_vec(&frame, LegacyDict::None).unwrap().0 == fixture.content);
}

/// The headers of the three formats: version, size, window and content size.
#[test]
fn headers_read_their_fields() {
    // v0.5: magic, then a window descriptor of log 11 + 1.
    let v05 = read_header(&[0x25, 0xB5, 0x2F, 0xFD, 0x01]).unwrap();
    assert_eq!(
        (v05.version, v05.size, v05.window, v05.content_size),
        (LegacyVersion::V05, 5, 1 << 12, None)
    );
    // v0.5 reserves the descriptor's high nibble.
    assert_eq!(
        read_header(&[0x25, 0xB5, 0x2F, 0xFD, 0x10]).unwrap_err(),
        Error::UnsupportedParameter
    );
    // v0.6: a one-byte content size of 200, window log 12 + 3.
    let v06 = read_header(&[0x26, 0xB5, 0x2F, 0xFD, 0x43, 200]).unwrap();
    assert_eq!(
        (v06.version, v06.size, v06.window, v06.content_size),
        (LegacyVersion::V06, 6, 1 << 15, Some(200))
    );
    // A two-byte content size counts from 256.
    let v06 = read_header(&[0x26, 0xB5, 0x2F, 0xFD, 0x80, 1, 0]).unwrap();
    assert_eq!(v06.content_size, Some(257));
    // v0.6 reserves bit 5.
    assert_eq!(
        read_header(&[0x26, 0xB5, 0x2F, 0xFD, 0x20]).unwrap_err(),
        Error::UnsupportedParameter
    );
    // v0.7: checksum, a one-byte dictionary ID, single segment with a
    // one-byte content size, which is also the window.
    let v07 = read_header(&[0x27, 0xB5, 0x2F, 0xFD, 0x25, 9, 100]).unwrap();
    assert_eq!(
        (
            v07.size,
            v07.window,
            v07.content_size,
            v07.dict_id,
            v07.checksum
        ),
        (7, 100, Some(100), 9, true)
    );
    // v0.7 reserves bit 3, and a header cut short is truncated.
    assert_eq!(
        read_header(&[0x27, 0xB5, 0x2F, 0xFD, 0x08, 0]).unwrap_err(),
        Error::UnsupportedParameter
    );
    assert_eq!(
        read_header(&[0x27, 0xB5, 0x2F, 0xFD, 0x25, 9]).unwrap_err(),
        Error::Truncated
    );
    // A window past the format's largest is refused.
    assert_eq!(
        read_header(&[0x27, 0xB5, 0x2F, 0xFD, 0x00, 0xF8]).unwrap_err(),
        Error::UnsupportedParameter
    );
}

/// An RFC 8878 frame and a frame of another magic number are not legacy.
#[test]
fn other_magic_numbers_are_not_legacy() {
    assert_eq!(LegacyVersion::of(&[0x28, 0xB5, 0x2F, 0xFD]), None);
    assert_eq!(LegacyVersion::of(&[0x24, 0xB5, 0x2F, 0xFD]), None);
    assert_eq!(LegacyVersion::of(&[0x25, 0xB5, 0x2F]), None);
    assert_eq!(declared_content_size(&[0x26, 0xB5, 0x2F, 0xFD, 0x43]), None);
}

/// v0.5 and v0.6 end a frame at any block whose body is empty, v0.7 only at
/// its end block: a raw block of no bytes is an empty block there.
#[test]
fn an_empty_block_ends_only_older_frames() {
    let empty_raw = [0x40, 0, 0];
    let end = [0xC0, 0, 0];
    let mut v06 = vec![0x26, 0xB5, 0x2F, 0xFD, 0x00];
    v06.extend_from_slice(&empty_raw);
    assert_eq!(frame_size(LegacyVersion::V06, &v06).unwrap(), (8, 0));
    let mut v07 = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    v07.extend_from_slice(&empty_raw);
    assert!(matches!(
        frame_size(LegacyVersion::V07, &v07),
        Err(FrameSizeError::Truncated)
    ));
    v07.extend_from_slice(&end);
    // A stored block bounds the content by its own size.
    assert_eq!(frame_size(LegacyVersion::V07, &v07).unwrap(), (12, 0));
    assert_eq!(
        decode_to_vec(&v07, LegacyDict::None).unwrap(),
        (Vec::new(), 12)
    );
}

/// The size walk measures a header from its size fields alone, as upstream's
/// does: a reserved bit the decoder refuses does not stop the walk.
#[test]
fn frame_size_reads_only_the_size_fields() {
    let end = [0xC0, 0, 0];
    // v0.6 with the reserved bit and a one-byte content size.
    let mut v06 = vec![0x26, 0xB5, 0x2F, 0xFD, 0x60, 9];
    v06.extend_from_slice(&end);
    assert_eq!(frame_size(LegacyVersion::V06, &v06).unwrap(), (9, 0));
    // v0.7 with the reserved bit, a two-byte dictionary ID and a window byte.
    let mut v07 = vec![0x27, 0xB5, 0x2F, 0xFD, 0x0A, 0, 1, 2];
    v07.extend_from_slice(&end);
    assert_eq!(frame_size(LegacyVersion::V07, &v07).unwrap(), (11, 0));
    // v0.7 single segment without a size field still carries one byte of it.
    let mut v07 = vec![0x27, 0xB5, 0x2F, 0xFD, 0x20, 7];
    v07.extend_from_slice(&end);
    assert_eq!(frame_size(LegacyVersion::V07, &v07).unwrap(), (9, 0));
    // v0.5 headers are five bytes whatever the descriptor says.
    let mut v05 = vec![0x25, 0xB5, 0x2F, 0xFD, 0xF0];
    v05.extend_from_slice(&end);
    assert_eq!(frame_size(LegacyVersion::V05, &v05).unwrap(), (8, 0));
    assert!(matches!(
        frame_size(LegacyVersion::V05, &v05[..4]),
        Err(FrameSizeError::Truncated)
    ));
}

/// A stream keeps its window and a block of history, not the whole frame:
/// a frame of a 1 KiB window and 1 MiB of blocks decodes in order while the
/// buffer stays within a few blocks.
#[test]
fn a_stream_holds_its_window_not_the_frame() {
    // v0.7, window byte 0: a 1 KiB window.
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    let mut expected = Vec::new();
    for n in 0..8u8 {
        let size = 128 * 1024 - 1;
        // A raw block of `size` bytes of `n`.
        frame.extend_from_slice(&[0x40 | (size >> 16) as u8, (size >> 8) as u8, size as u8]);
        frame.extend(core::iter::repeat_n(n, size));
        expected.extend(core::iter::repeat_n(n, size));
    }
    frame.extend_from_slice(&[0xC0, 0, 0]);
    let header = read_header(&frame).unwrap();
    let mut stream = LegacyStream::new();
    stream.start(header, None, FrameOptions::default()).unwrap();
    let mut src = &frame[header.size..];
    let mut out = Vec::new();
    let mut target = vec![0u8; 50_000];
    let mut largest = 0;
    while !(stream.is_finished() && stream.undelivered() == 0) {
        let (read, written) = stream.decode(src, &mut target).unwrap();
        src = &src[read..];
        out.extend_from_slice(&target[..written]);
        largest = largest.max(stream.heap_bytes());
        assert!(read > 0 || written > 0);
    }
    assert!(src.is_empty());
    assert!(out == expected);
    assert_eq!(stream.produced(), expected.len() as u64);
    assert_eq!(stream.consumed(), frame.len() as u64);
    assert!(largest <= 4 * BLOCK_SIZE_MAX, "held {largest} bytes");
}

/// A frame several windows long decodes through the stream with its matches
/// reaching into the segment before the current one, the buffer never past
/// the window and a block.
#[cfg(feature = "std")]
#[test]
fn a_stream_reads_matches_from_the_segment_before() {
    for fixture in fixtures()
        .into_iter()
        .filter(|f| f.name.starts_with("z000000x8."))
    {
        let header = read_header(&fixture.frame).unwrap();
        let capacity = header.window as usize + BLOCK_SIZE_MAX;
        assert!(
            fixture.content.len() > 2 * capacity,
            "{}: the frame must outrun the buffer",
            fixture.name
        );
        let mut stream = LegacyStream::new();
        stream.start(header, None, FrameOptions::default()).unwrap();
        let mut src = &fixture.frame[header.size..];
        let mut out = Vec::new();
        let mut target = vec![0u8; 4096];
        while !(stream.is_finished() && stream.undelivered() == 0) {
            let (read, written) = stream
                .decode(src, &mut target)
                .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
            assert!(read > 0 || written > 0, "{} stalled", fixture.name);
            src = &src[read..];
            out.extend_from_slice(&target[..written]);
        }
        assert!(out == fixture.content, "{}", fixture.name);
        assert!(
            stream.buf.capacity() <= capacity,
            "{}: held {} bytes for a window of {}",
            fixture.name,
            stream.buf.capacity(),
            header.window
        );
    }
}

/// The fixture of this name.
#[cfg(feature = "std")]
fn fixture(name: &str) -> fixtures::Fixture {
    fixtures()
        .into_iter()
        .find(|f| f.name == name)
        .unwrap_or_else(|| panic!("no fixture {name}"))
}

/// A fresh decoder handed one of these frames by `decode_from_to` starts it
/// itself, as it starts an RFC 8878 frame, and decodes it to its content.
#[cfg(feature = "std")]
#[test]
fn decode_from_to_starts_these_frames_on_a_fresh_decoder() {
    use crate::decoding::FrameDecoder;
    for name in [
        "abc.txt.v05.l1.zst",
        "z000001.v06.l19.zst",
        "z000001.v07.l19.zst",
    ] {
        let fixture = fixture(name);
        let mut decoder = FrameDecoder::new();
        let mut src = &fixture.frame[..];
        let mut out = Vec::new();
        let mut target = [0u8; 500];
        loop {
            let (read, written) = decoder
                .decode_from_to(src, &mut target)
                .unwrap_or_else(|err| panic!("{name}: {err}"));
            src = &src[read..];
            out.extend_from_slice(&target[..written]);
            if decoder.is_finished() && decoder.can_collect() == 0 {
                break;
            }
            assert!(read > 0 || written > 0, "{name} stalled");
        }
        assert!(src.is_empty(), "{name}");
        assert!(out == fixture.content, "{name}");
    }
}

/// The checksum mode applies to a v0.7 frame's 22-bit checksum as to an
/// RFC 8878 frame's: `Verify` refuses a frame whose content does not match
/// it, `EmitOnly` decodes it and exposes both values, `None` computes
/// nothing.
#[cfg(all(feature = "std", feature = "hash"))]
#[test]
fn the_checksum_mode_applies_to_v07_frames() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{BlockDecodingStrategy, ContentChecksum, FrameDecoder};
    let fixture = fixture("abc.txt.v07.l1.zst");
    let mut frame = fixture.frame.clone();
    let last = frame.len() - 1;
    frame[last] ^= 1;
    let end = &frame[frame.len() - 3..];
    let stored = u32::from(end[2]) | u32::from(end[1]) << 8 | u32::from(end[0] & 0x3F) << 16;
    let run = |mode| {
        let mut decoder = FrameDecoder::new();
        decoder.set_content_checksum(mode);
        let mut src = &frame[..];
        decoder.reset(&mut src)?;
        decoder.decode_blocks(&mut src, BlockDecodingStrategy::All)?;
        let content = decoder.collect().unwrap();
        Ok::<_, FrameDecoderError>((
            content,
            decoder.get_checksum_from_data(),
            decoder.get_calculated_checksum(),
        ))
    };
    assert!(matches!(
        run(ContentChecksum::Verify),
        Err(FrameDecoderError::LegacyFrame(
            Error::ChecksumMismatch { .. }
        ))
    ));
    let (content, from_data, calculated) = run(ContentChecksum::EmitOnly).unwrap();
    assert!(content == fixture.content);
    assert_eq!(from_data, Some(stored));
    assert!(calculated.is_some_and(|calculated| calculated != stored));
    let (content, _, calculated) = run(ContentChecksum::None).unwrap();
    assert!(content == fixture.content);
    assert_eq!(calculated, None);

    // The same on the whole-buffer path.
    let mut out = vec![0u8; fixture.content.len()];
    let mut decoder = FrameDecoder::new();
    decoder.set_content_checksum(ContentChecksum::Verify);
    assert!(decoder.decode_all(&frame, &mut out).is_err());
    for mode in [ContentChecksum::EmitOnly, ContentChecksum::None] {
        decoder.set_content_checksum(mode);
        assert_eq!(
            decoder.decode_all(&frame, &mut out).unwrap(),
            fixture.content.len()
        );
    }
}

/// A checksum mode set after `reset`, before the frame's first block, applies
/// to the frame, as it applies to an RFC 8878 frame's: turned to `Verify` it
/// refuses a damaged frame, turned to `None` it computes nothing.
#[cfg(all(feature = "std", feature = "hash"))]
#[test]
fn a_checksum_mode_set_after_reset_applies() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{BlockDecodingStrategy, ContentChecksum, FrameDecoder};
    let fixture = fixture("abc.txt.v07.l1.zst");
    let mut frame = fixture.frame.clone();
    let last = frame.len() - 1;
    frame[last] ^= 1;
    let run = |before, after| {
        let mut decoder = FrameDecoder::new();
        decoder.set_content_checksum(before);
        let mut src = &frame[..];
        decoder.reset(&mut src)?;
        decoder.set_content_checksum(after);
        decoder.decode_blocks(&mut src, BlockDecodingStrategy::All)?;
        let content = decoder.collect().unwrap();
        Ok::<_, FrameDecoderError>((content, decoder.get_calculated_checksum()))
    };
    assert!(matches!(
        run(ContentChecksum::None, ContentChecksum::Verify),
        Err(FrameDecoderError::LegacyFrame(
            Error::ChecksumMismatch { .. }
        ))
    ));
    let (content, calculated) = run(ContentChecksum::Verify, ContentChecksum::None).unwrap();
    assert!(content == fixture.content);
    assert_eq!(calculated, None);
}

/// The calls that take RFC 8878 blocks refuse while one of these frames is
/// the current one, even on a decoder that still holds an RFC 8878 frame it
/// left before its last block: that frame is not the one the caller started,
/// and its blocks are not these. The frame itself still decodes afterwards.
#[cfg(feature = "std")]
#[test]
fn block_calls_refuse_these_frames_on_a_reused_decoder() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    use crate::encoding::{CompressionLevel, compress_to_vec};
    let fixture = fixture("z000001.v07.l19.zst");
    let rfc = compress_to_vec(&[7u8; 300_000][..], CompressionLevel::Fastest);
    let mut decoder = FrameDecoder::new();
    let mut rfc_src = rfc.as_slice();
    decoder.reset(&mut rfc_src).unwrap();
    // The RFC 8878 frame is left with every block still to come.
    let mut src = &fixture.frame[..];
    decoder.reset(&mut src).unwrap();
    let header = *rfc_src.first_chunk::<3>().unwrap();
    let mut out = [0u8; 64];
    assert!(matches!(
        decoder.block_content_len(header),
        Err(FrameDecoderError::NotYetInitialized)
    ));
    assert!(matches!(
        decoder.decode_block(header, &rfc_src[3..], &mut out),
        Err(FrameDecoderError::NotYetInitialized)
    ));
    assert!(matches!(
        decoder.insert_block(b"history"),
        Err(FrameDecoderError::NotYetInitialized)
    ));
    #[cfg(feature = "lsm")]
    assert!(matches!(
        decoder.decode_blocks_partial(&mut &src[..], 0, 1, None, false),
        Err(FrameDecoderError::NotYetInitialized)
    ));
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert!(decoder.collect().unwrap() == fixture.content);
}

/// A whole-buffer decode ends one of these frames a `Read`-driven reset
/// started even when the header it meets does not read: a skippable frame,
/// a damaged RFC 8878 header. The decoder no longer reports or decodes the
/// abandoned frame.
#[cfg(feature = "std")]
#[test]
fn a_header_that_fails_on_a_slice_ends_these_frames() {
    use crate::decoding::{DictionaryHandle, FrameDecoder};
    let fixture = fixture("z000001.v07.l19.zst");
    let skippable = [0x50, 0x2A, 0x4D, 0x18, 0, 0, 0, 0];
    let damaged = [0x28, 0xB5, 0x2F, 0xFD, 0x08];
    let dict = DictionaryHandle::from_serialized_or_raw_content(b"raw dictionary content").unwrap();
    for (input, with_dict) in [
        (&skippable[..], false),
        (&damaged[..], false),
        (&skippable[..], true),
        (&damaged[..], true),
    ] {
        let mut decoder = FrameDecoder::new();
        decoder.reset(&fixture.frame[..]).unwrap();
        assert_eq!(decoder.input_needed(&[]), 3);
        let mut out = [0u8; 16];
        let _ = if with_dict {
            decoder.decode_all_with_dict_handle(input, &mut out, &dict)
        } else {
            decoder.decode_all(input, &mut out)
        };
        assert_eq!(decoder.input_needed(&[]), 0, "{input:02x?} {with_dict}");
        assert!(decoder.is_finished(), "{input:02x?} {with_dict}");
    }
}

/// A block limit set on the decoder holds these frames' blocks to it, on
/// both paths.
#[cfg(feature = "std")]
#[test]
fn the_block_limit_applies_to_these_frames() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    for name in [
        "z000000.v05.l1.zst",
        "z000000.v06.l1.zst",
        "z000000.v07.l1.zst",
    ] {
        let fixture = fixture(name);
        let mut decoder = FrameDecoder::new();
        decoder.set_max_block_size(Some(1024));
        let mut out = vec![0u8; fixture.content.len()];
        assert!(
            matches!(
                decoder.decode_all(&fixture.frame, &mut out),
                Err(FrameDecoderError::LegacyFrame(_))
            ),
            "{name}"
        );
        let mut src = &fixture.frame[..];
        decoder.reset(&mut src).unwrap();
        assert!(
            matches!(
                decoder.decode_blocks(&mut src, BlockDecodingStrategy::All),
                Err(FrameDecoderError::LegacyFrame(_))
            ),
            "{name}"
        );
        decoder.set_max_block_size(None);
        assert_eq!(
            decoder.decode_all(&fixture.frame, &mut out).unwrap(),
            out.len(),
            "{name}"
        );
    }
}

/// A stored block (raw, or RLE in v0.7) may run to its 19-bit size field,
/// past the 128 KiB a compressed block holds, as libzstd's one-shot decoders
/// take it (`ZSTDv0{6,7}_decompressFrame` check only the output's room): on
/// every path, with the size queries bounding it. A block limit the caller
/// lowered holds stored blocks to it as well.
#[cfg(feature = "std")]
#[test]
fn stored_blocks_run_past_the_compressed_block_maximum() {
    use crate::decoding::{
        BlockDecodingStrategy, FrameDecoder, StreamingDecoder, find_frame_compressed_size,
        frame_decompressed_bound,
    };
    use std::io::Read;
    let raw: Vec<u8> = (0..131_073u32).map(|n| (n % 251) as u8).collect();
    let rle = 200_000usize;
    // v0.7 header: a window byte, no dictionary, no size, no checksum.
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    frame.extend_from_slice(&[0x40 | 0x02, 0x00, 0x01]);
    frame.extend_from_slice(&raw);
    frame.extend_from_slice(&[0x80 | 0x03, 0x0D, 0x40, 0x7E]);
    frame.extend_from_slice(&[0xC0, 0x00, 0x00]);
    let mut content = raw.clone();
    content.resize(raw.len() + rle, 0x7E);

    assert_eq!(find_frame_compressed_size(&frame).unwrap(), frame.len());
    assert!(frame_decompressed_bound(&frame).unwrap() >= content.len() as u64);

    let mut out = vec![0u8; content.len()];
    let mut decoder = FrameDecoder::new();
    assert_eq!(decoder.decode_all(&frame, &mut out).unwrap(), content.len());
    assert!(out == content);

    let mut src = &frame[..];
    decoder.reset(&mut src).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert!(decoder.collect().unwrap() == content);

    let mut streamed = Vec::new();
    StreamingDecoder::new(&frame[..])
        .read_to_end(&mut streamed)
        .unwrap();
    assert!(streamed == content);

    decoder.set_max_block_size(Some(64 * 1024));
    assert!(decoder.decode_all(&frame, &mut out).is_err());
}

/// A window ceiling lowered under a started frame's window refuses its next
/// step, as it refuses an RFC 8878 frame's.
#[cfg(feature = "std")]
#[test]
fn a_lowered_window_ceiling_binds_a_started_frame() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    let fixture = fixture("z000000.v07.l1.zst");
    let window = read_header(&fixture.frame).unwrap().window;
    let mut decoder = FrameDecoder::new();
    let mut src = &fixture.frame[..];
    decoder.reset(&mut src).unwrap();
    decoder.set_max_window_size(window / 2).unwrap();
    assert!(matches!(
        decoder.decode_blocks(&mut src, BlockDecodingStrategy::All),
        Err(FrameDecoderError::WindowSizeTooBig { requested, limit })
            if requested == window && limit == window / 2
    ));
    let mut target = [0u8; 64];
    assert!(matches!(
        decoder.decode_from_to(src, &mut target),
        Err(FrameDecoderError::WindowSizeTooBig { .. })
    ));
    // Raised again, the frame decodes on.
    decoder.set_max_window_size(window).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert!(decoder.collect().unwrap() == fixture.content);

    // A ceiling below the window refuses the frame from its header.
    decoder.set_max_window_size(window / 2).unwrap();
    assert!(matches!(
        decoder.reset(&fixture.frame[..]),
        Err(FrameDecoderError::WindowSizeTooBig { requested, limit })
            if requested == window && limit == window / 2
    ));
}

/// The decoder's accessors describe a started frame of these formats: its
/// declared content size, and the blocks decoded so far, not what the frame
/// before left.
#[cfg(feature = "std")]
#[test]
fn the_accessors_describe_these_frames() {
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    let rfc = crate::encoding::compress_slice_to_vec(
        &[7u8; 500],
        crate::encoding::CompressionLevel::Fastest,
    );
    let mut decoder = FrameDecoder::new();
    let mut src = &rfc[..];
    decoder.reset(&mut src).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert_eq!(decoder.content_size(), 500);

    // v0.6.2 declares its first chunk's size.
    let v06 = fixture("z000000.v06.l1.zst");
    let mut src = &v06.frame[..];
    decoder.reset(&mut src).unwrap();
    assert_eq!(decoder.content_size(), 128 * 1024);
    assert_eq!(decoder.blocks_decoded(), 0);
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    let (_, bound) = frame_size(LegacyVersion::V06, &v06.frame).unwrap();
    assert_eq!(
        decoder.blocks_decoded() as u64,
        bound / BLOCK_SIZE_MAX as u64
    );
    // The stream's buffers, past a block of output, count toward the
    // decoder's footprint.
    assert!(decoder.workspace_size() > BLOCK_SIZE_MAX);

    // v0.5 declares none.
    let v05 = fixture("abc.txt.v05.l1.zst");
    let mut src = &v05.frame[..];
    decoder.reset(&mut src).unwrap();
    assert_eq!(decoder.content_size(), 0);
}

/// Each failure carries the code libzstd returns for it, and keeps that code,
/// its message and itself as the source when the frame decoder wraps it.
#[cfg(feature = "std")]
#[test]
fn errors_report_libzstd_codes() {
    use crate::decoding::errors::{ErrorCode, FrameDecoderError};
    use std::error::Error as _;
    use std::string::ToString;
    let cases = [
        // A cut frame is a source of the wrong size, as libzstd reports it
        // (`ZSTD_findFrameSizeInfoLegacy`), not a damaged one.
        (Error::Truncated, ErrorCode::SrcSizeWrong, "ends inside"),
        (
            Error::UnsupportedParameter,
            ErrorCode::FrameParameterUnsupported,
            "unsupported setting",
        ),
        (
            Error::Corrupted {
                reason: "bad table",
            },
            ErrorCode::CorruptionDetected,
            "bad table",
        ),
        (
            Error::OutputTooSmall,
            ErrorCode::DstSizeTooSmall,
            "too small",
        ),
        (
            Error::DictionaryCorrupted,
            ErrorCode::DictionaryCorrupted,
            "dictionary could not be read",
        ),
        (
            Error::DictionaryMismatch {
                expected: 0xAB,
                provided: 0,
            },
            ErrorCode::DictionaryWrong,
            "dictionary 0xAB",
        ),
        (
            Error::ChecksumMismatch {
                expected: 1,
                calculated: 2,
            },
            ErrorCode::ChecksumWrong,
            "0x000001",
        ),
    ];
    // libzstd's own message for the code a cut frame carries.
    assert_eq!(ErrorCode::SrcSizeWrong.message(), "Src size is incorrect");
    for (err, code, text) in cases {
        assert_eq!(err.code(), code, "{err:?}");
        let message = err.to_string();
        assert!(message.contains(text), "{message}");
        let wrapped = FrameDecoderError::from(err);
        assert_eq!(wrapped.code(), code);
        assert_eq!(wrapped.to_string(), message);
        assert!(
            wrapped
                .source()
                .is_some_and(|source| source.to_string() == message)
        );
    }
}

/// After `decode_all` the accessors describe the frame it decoded last, as
/// they do an RFC 8878 one, not the frame decoded before it.
#[cfg(feature = "std")]
#[test]
fn the_accessors_describe_a_frame_decoded_whole() {
    use crate::decoding::FrameDecoder;
    let rfc = crate::encoding::compress_slice_to_vec(
        &[7u8; 500],
        crate::encoding::CompressionLevel::Fastest,
    );
    let v06 = fixture("z000000.v06.l1.zst");
    let mut decoder = FrameDecoder::new();
    let mut out = vec![0u8; v06.content.len()];
    decoder.decode_all(&rfc, &mut out).unwrap();
    assert_eq!(decoder.content_size(), 500);

    assert_eq!(
        decoder.decode_all(&v06.frame, &mut out).unwrap(),
        v06.content.len()
    );
    let (_, bound) = frame_size(LegacyVersion::V06, &v06.frame).unwrap();
    assert_eq!(decoder.content_size(), 128 * 1024);
    assert_eq!(
        decoder.blocks_decoded() as u64,
        bound / BLOCK_SIZE_MAX as u64
    );
    assert_eq!(decoder.bytes_read_from_source(), v06.frame.len() as u64);
    assert!(decoder.is_finished());
    assert_eq!(decoder.can_collect(), 0);

    #[cfg(feature = "hash")]
    {
        let v07 = fixture("abc.txt.v07.l1.zst");
        let end = &v07.frame[v07.frame.len() - 3..];
        let stored = u32::from(end[2]) | u32::from(end[1]) << 8 | u32::from(end[0] & 0x3F) << 16;
        decoder.decode_all(&v07.frame, &mut out).unwrap();
        assert_eq!(decoder.get_checksum_from_data(), Some(stored));
        assert_eq!(decoder.get_calculated_checksum(), Some(stored));
    }
}

/// Per-block checksums cover these frames' blocks on every path, as they
/// cover an RFC 8878 frame's.
#[cfg(all(feature = "std", feature = "lsm", feature = "hash"))]
#[test]
fn per_block_checksums_cover_these_frames() {
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    // One data block: its digest is the content's.
    let one = fixture("abc.txt.v07.l1.zst");
    let digest = twox_hash::XxHash64::oneshot(0, &one.content) as u32;
    let many = fixture("z000000.v07.l1.zst");
    let (_, bound) = frame_size(LegacyVersion::V07, &many.frame).unwrap();
    let blocks = (bound / BLOCK_SIZE_MAX as u64) as usize;

    let mut decoder = FrameDecoder::new();
    decoder.enable_per_block_checksums();
    let mut out = vec![0u8; many.content.len()];
    decoder.decode_all(&one.frame, &mut out).unwrap();
    assert_eq!(decoder.computed_block_checksums(), [digest]);
    decoder.decode_all(&many.frame, &mut out).unwrap();
    assert_eq!(decoder.computed_block_checksums().len(), blocks);

    let mut src = &one.frame[..];
    decoder.reset(&mut src).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert_eq!(decoder.computed_block_checksums(), [digest]);
}

/// A pinned dictionary ID or window descriptor holds these frames to it, on
/// both paths: v0.7 carries both fields, v0.5 and v0.6 neither.
#[cfg(all(feature = "std", feature = "lsm"))]
#[test]
fn pinned_header_fields_bind_these_frames() {
    use crate::decoding::FrameDecoder;
    use crate::decoding::errors::FrameDecoderError;
    let v07 = fixture("z000000x8.v07.l1.zst");
    // Not single-segment: the window byte follows the descriptor.
    assert_eq!(v07.frame[4] & 0x20, 0);
    let window = v07.frame[5];
    let v05 = fixture("abc.txt.v05.l1.zst");
    let mut out = vec![0u8; v07.content.len()];

    let mut decoder = FrameDecoder::new();
    decoder.expect_dict_id(Some(5));
    assert!(matches!(
        decoder.decode_all(&v07.frame, &mut out),
        Err(FrameDecoderError::UnexpectedDictId {
            expected: Some(5),
            found: None
        })
    ));
    assert!(matches!(
        decoder.reset(&v07.frame[..]),
        Err(FrameDecoderError::UnexpectedDictId { .. })
    ));
    decoder.expect_dict_id(Some(0));
    decoder.expect_window_descriptor(Some(window ^ 1));
    assert!(matches!(
        decoder.decode_all(&v07.frame, &mut out),
        Err(FrameDecoderError::UnexpectedWindowDescriptor { found: Some(w), .. }) if w == window
    ));
    assert!(matches!(
        decoder.reset(&v05.frame[..]),
        Err(FrameDecoderError::UnexpectedWindowDescriptor { found: None, .. })
    ));
    decoder.expect_window_descriptor(Some(window));
    assert_eq!(
        decoder.decode_all(&v07.frame, &mut out).unwrap(),
        v07.content.len()
    );
}

/// A v0.5-v0.7 magic number with nothing after it is a truncated frame to
/// the aggregate size query, as upstream's `ZSTD_findDecompressedSize`
/// refuses a tail shorter than a frame's first five bytes.
#[cfg(feature = "std")]
#[test]
fn a_bare_magic_number_is_a_truncated_frame() {
    use crate::decoding::find_decompressed_size;
    let magic = [0x27, 0xB5, 0x2F, 0xFD];
    assert!(find_decompressed_size(&magic).is_err());
    let mut stream = fixture("z000000.v07.l1.zst").frame;
    stream.extend_from_slice(&magic);
    assert!(find_decompressed_size(&stream).is_err());
}

/// A reader failing after the magic number hands its own error back, in the
/// header field it failed in, rather than calling the frame truncated.
#[cfg(feature = "std")]
#[test]
fn reader_errors_inside_the_header_are_kept() {
    use crate::decoding::FrameDecoder;
    use crate::decoding::errors::{FrameDecoderError, ReadFrameHeaderError};
    struct Stalls<'a>(&'a [u8]);
    impl std::io::Read for Stalls<'_> {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if self.0.is_empty() {
                return Err(std::io::ErrorKind::WouldBlock.into());
            }
            let n = buf.len().min(self.0.len());
            buf[..n].copy_from_slice(&self.0[..n]);
            self.0 = &self.0[n..];
            Ok(n)
        }
    }
    let mut decoder = FrameDecoder::new();
    let err = decoder
        .reset(Stalls(&[0x27, 0xB5, 0x2F, 0xFD]))
        .unwrap_err();
    assert!(
        matches!(
            &err,
            FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::FrameDescriptorReadError(e))
                if e.kind() == std::io::ErrorKind::WouldBlock
        ),
        "{err:?}"
    );
    // v0.7 with a window byte still to come.
    let err = decoder
        .reset(Stalls(&[0x27, 0xB5, 0x2F, 0xFD, 0x00]))
        .unwrap_err();
    assert!(
        matches!(
            &err,
            FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::WindowDescriptorReadError(e))
                if e.kind() == std::io::ErrorKind::WouldBlock
        ),
        "{err:?}"
    );
    // v0.7 with its window byte read and a one-byte dictionary ID to come.
    let err = decoder
        .reset(Stalls(&[0x27, 0xB5, 0x2F, 0xFD, 0x01, 0x00]))
        .unwrap_err();
    assert!(
        matches!(
            &err,
            FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::DictionaryIdReadError(e))
                if e.kind() == std::io::ErrorKind::WouldBlock
        ),
        "{err:?}"
    );
    // v0.6 with a two-byte content size still to come.
    let err = decoder
        .reset(Stalls(&[0x26, 0xB5, 0x2F, 0xFD, 0x80, 1]))
        .unwrap_err();
    assert!(
        matches!(
            &err,
            FrameDecoderError::ReadFrameHeaderError(ReadFrameHeaderError::FrameContentSizeReadError(e))
                if e.kind() == std::io::ErrorKind::WouldBlock
        ),
        "{err:?}"
    );
}

/// The stream counts in its footprint the entropy tables and literal buffer
/// its frame holds, not only its output buffer.
#[cfg(feature = "std")]
#[test]
fn the_stream_footprint_counts_its_tables() {
    for name in [
        "z000000.v05.l1.zst",
        "z000000.v06.l1.zst",
        "z000000.v07.l1.zst",
    ] {
        let fixture = fixture(name);
        let header = read_header(&fixture.frame).unwrap();
        let mut stream = LegacyStream::new();
        stream.start(header, None, FrameOptions::default()).unwrap();
        let mut target = vec![0u8; fixture.content.len()];
        stream
            .decode(&fixture.frame[header.size..], &mut target)
            .unwrap();
        assert!(
            stream.heap_bytes() > stream.buf.capacity() + stream.block.capacity(),
            "{name}: {} bytes held, {} of them the output buffer",
            stream.heap_bytes(),
            stream.buf.capacity()
        );
    }
}

/// A block whose header declares more than its type's limit is refused from
/// the header alone: the stream asks for no more than it. A stored block
/// runs to its size field unless the caller lowered the limit.
#[test]
fn an_oversized_block_is_refused_from_its_header() {
    // v0.7 with a 1 KiB window.
    let frame = [0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    let header = read_header(&frame).unwrap();
    let compressed = [0x03, 0xFF, 0xFF];
    let raw = [0x40 | 0x03, 0xFF, 0xFF];
    let mut stream = LegacyStream::new();
    stream.start(header, None, FrameOptions::default()).unwrap();
    // Less than a block header asks for the header.
    assert_eq!(stream.input_needed(&[0x40]), 3);
    // A compressed block of 0x3FFFF bytes.
    assert_eq!(stream.input_needed(&compressed), 3);
    assert!(stream.decode(&compressed, &mut [0u8; 16]).is_err());
    // A raw one of the same size is a whole block to read.
    let mut stream = LegacyStream::new();
    stream.start(header, None, FrameOptions::default()).unwrap();
    assert_eq!(stream.input_needed(&raw), 3 + 0x3FFFF);
    // Under a lowered limit, it is refused from its header too.
    let lowered = FrameOptions {
        block_max: 64 * 1024,
        ..FrameOptions::default()
    };
    let mut stream = LegacyStream::new();
    stream.start(header, None, lowered).unwrap();
    assert_eq!(stream.input_needed(&raw), 3);
    assert!(stream.decode(&raw, &mut [0u8; 16]).is_err());
}

/// A v0.7 block whose sequence tables are each one symbol decodes, and one
/// naming a symbol past its field is refused.
#[test]
fn one_symbol_sequence_tables_decode_in_v07() {
    // Raw literals "a"; one sequence; every table one symbol: literal length
    // code 1, offset code 2 (two extra bits, here 0, so offset 1), match
    // length code 0 (3 bytes). The bitstream holds those two bits under its
    // end mark.
    let block = [0x81, b'a', 0x01, 0x54, 1, 2, 0, 0x04];
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00, 0x00, 0x00];
    frame.push(block.len() as u8);
    frame.extend_from_slice(&block);
    frame.extend_from_slice(&[0xC0, 0, 0]);
    assert_eq!(decode_to_vec(&frame, LegacyDict::None).unwrap().0, b"aaaa");
    // A match length symbol past the field's largest.
    let at = frame.len() - 4;
    frame[at - 1] = 200;
    assert!(matches!(
        decode_to_vec(&frame, LegacyDict::None),
        Err(Error::Corrupted { .. })
    ));
}

/// A sequence count takes one byte below 0x80, two up to 0x7EFF, and three
/// after a 0xFF where the format allows them.
#[test]
fn sequence_counts_take_their_forms() {
    assert_eq!(v07::sequence_count(&[0x7F], true).unwrap(), (0x7F, 1));
    assert_eq!(
        v07::sequence_count(&[0x81, 0x02], true).unwrap(),
        (0x102, 2)
    );
    assert_eq!(
        v07::sequence_count(&[0xFF, 0x01, 0x00], true).unwrap(),
        (0x7F01, 3)
    );
    assert_eq!(
        v07::sequence_count(&[0xFF, 0x01], false).unwrap(),
        (0x7F01, 2)
    );
    assert!(v07::sequence_count(&[], true).is_err());
    assert!(v07::sequence_count(&[0xFF, 0x01], true).is_err());
    assert!(v07::sequence_count(&[0x80], true).is_err());
}

/// The version queries: each format's minor version, and a header's length
/// from its size fields once the descriptor is in hand.
#[test]
fn versions_answer_their_queries() {
    assert_eq!(LegacyVersion::V05.minor(), 5);
    assert_eq!(LegacyVersion::V06.minor(), 6);
    assert_eq!(LegacyVersion::V07.minor(), 7);
    let v05 = [0x25, 0xB5, 0x2F, 0xFD, 0x01];
    assert_eq!(LegacyVersion::V05.header_size(&v05[..4]), None);
    assert_eq!(LegacyVersion::V05.header_size(&v05), Some(5));
    // v0.6 with a two-byte content size.
    assert_eq!(
        LegacyVersion::V06.header_size(&[0x26, 0xB5, 0x2F, 0xFD, 0x80]),
        Some(7)
    );
    // v0.7, single-segment with an eight-byte content size and a four-byte
    // dictionary ID.
    assert_eq!(
        LegacyVersion::V07.header_size(&[0x27, 0xB5, 0x2F, 0xFD, 0xE3]),
        Some(17)
    );
}

/// A literal section header the block cannot hold, or one past the largest
/// block, is refused before anything decodes.
#[test]
fn literal_headers_refuse_what_does_not_fit() {
    for header in [
        // Huffman literals with less than their five-byte minimum.
        &[0x00, 0, 0, 0][..],
        // Huffman literals declaring more than a block.
        &[0x3F, 0xFF, 0xFC, 0, 0, 0],
        // Huffman literals running past the block.
        &[0x00, 0x04, 0xFF, 0, 0],
        // Repeated-table literals in a form other than the small one.
        &[0x40, 0, 0],
        // Repeated-table literals running past the block.
        &[0x50, 0x03, 0xFF],
        // Raw literals running past the block.
        &[0x9F, 0, 0],
        // A run with a three-byte header and nothing after it.
        &[0xF0, 0, 0],
        // A run longer than a block.
        &[0xFF, 0xFF, 0xFF, 0],
        // Less than any literal section.
        &[0x80, 0],
    ] {
        assert!(
            matches!(Literals::read(header), Err(Error::Corrupted { .. })),
            "{header:02X?}"
        );
    }
}

/// A block's budget passes everything but its size check to the output it
/// guards.
#[cfg(feature = "hash")]
#[test]
fn a_budget_passes_through_to_its_output() {
    let mut buf = Vec::new();
    let mut inner = VecOutput {
        buf: &mut buf,
        start: 0,
    };
    let mut out = Budget {
        out: &mut inner,
        end: 8,
    };
    out.reserve(2).unwrap();
    out.extend(b"ab");
    out.repeat(b'c', 2);
    out.copy_back(4, 2);
    assert_eq!((out.produced(), out.held()), (6, 6));
    assert_eq!(out.since(2), b"ccab");
    assert!(out.reserve(3).is_err());
    out.copy_match(
        1,
        2,
        &History {
            head: &[],
            tail: &[],
        },
    )
    .unwrap();
    assert_eq!(buf, b"abccabbb");
}

/// A match into a dictionary held in two pieces reads across them, and on
/// into the frame's own output past their end.
#[test]
fn matches_read_a_history_in_two_pieces() {
    let history = History {
        head: b"ab",
        tail: b"cd",
    };
    let mut buf = Vec::new();
    let mut out = VecOutput {
        buf: &mut buf,
        start: 0,
    };
    // From the second byte of the head, across into the tail.
    out.copy_match(3, 2, &history).unwrap();
    // Back into the tail's first byte, past its end into the frame.
    out.copy_match(5, 4, &history).unwrap();
    // Six bytes out and four of dictionary: an offset of eleven reaches
    // before both.
    assert!(out.copy_match(11, 1, &history).is_err());
    assert_eq!(buf, b"bcbcdb");
}

/// The size walk refuses a frame cut inside a block's body.
#[cfg(feature = "std")]
#[test]
fn frame_size_refuses_a_cut_block() {
    let fixture = fixture("z000000.v07.l1.zst");
    let frame = &fixture.frame[..fixture.frame.len() - 10];
    assert!(matches!(
        frame_size(LegacyVersion::V07, frame),
        Err(FrameSizeError::Truncated)
    ));
}

/// An RLE block decodes into a caller's slice and through a stream as it
/// does into a vector.
#[cfg(feature = "std")]
#[test]
fn rle_blocks_decode_on_every_path() {
    use crate::decoding::FrameDecoder;
    let frame = [
        0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00, 0x80, 0, 5, b'z', 0xC0, 0, 0,
    ];
    let mut out = [0u8; 5];
    assert_eq!(FrameDecoder::new().decode_all(&frame, &mut out).unwrap(), 5);
    assert_eq!(&out, b"zzzzz");
    let mut decoder = FrameDecoder::new();
    let mut target = [0u8; 8];
    let (read, written) = decoder.decode_from_to(&frame, &mut target).unwrap();
    assert_eq!((read, &target[..written]), (frame.len(), &b"zzzzz"[..]));
}

/// A `Read` source failing inside a block hands back its own error, in the
/// block header or the body it failed in.
#[cfg(feature = "std")]
#[test]
fn reader_errors_inside_a_block_are_kept() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    let fixture = fixture("z000000.v07.l1.zst");
    let header = read_header(&fixture.frame).unwrap();
    for (cut, header_error) in [(header.size + 1, true), (header.size + 4, false)] {
        let mut decoder = FrameDecoder::new();
        let mut src = &fixture.frame[..cut];
        decoder.reset(&mut src).unwrap();
        let err = decoder
            .decode_blocks(&mut src, BlockDecodingStrategy::All)
            .unwrap_err();
        if header_error {
            assert!(
                matches!(err, FrameDecoderError::FailedToReadBlockHeader(_)),
                "{err:?}"
            );
        } else {
            assert!(
                matches!(err, FrameDecoderError::FailedToReadBlockBody(_)),
                "{err:?}"
            );
        }
    }
}

/// `read_to_end` over an RFC 8878 frame and then a v0.7 one decodes both
/// with the dictionary the reader was forced to, and hands out nothing of a
/// v0.7 frame that fails.
#[cfg(feature = "std")]
#[test]
fn read_to_end_keeps_a_forced_dictionary_for_these_frames() {
    use crate::decoding::{DictionaryHandle, StreamingDecoder};
    use std::io::Read;
    let v07 = fixture("ModemManager.service.v07.dict.zst");
    let dict =
        DictionaryHandle::from_serialized_or_raw_content(v07.dict.as_deref().unwrap()).unwrap();
    let leading = b"a leading frame";
    let mut input =
        crate::encoding::compress_slice_to_vec(leading, crate::encoding::CompressionLevel::Fastest);
    let rfc_len = input.len();
    input.extend_from_slice(&v07.frame);
    let mut out = Vec::new();
    StreamingDecoder::new_with_dictionary_handle(&input[..], &dict)
        .unwrap()
        .read_to_end(&mut out)
        .unwrap();
    let mut expected = leading.to_vec();
    expected.extend_from_slice(&v07.content);
    assert!(out == expected);

    // The v0.7 frame cut short: its bytes are not handed out.
    let cut = &input[..input.len() - 1];
    assert!(cut.len() > rfc_len);
    let mut out = Vec::new();
    assert!(
        StreamingDecoder::new_with_dictionary_handle(cut, &dict)
            .unwrap()
            .read_to_end(&mut out)
            .is_err()
    );
    assert_eq!(out, leading);
}

/// `force_dict` gives a started v0.7 frame that names no dictionary the
/// registered one, as it does an RFC 8878 frame, and `dictionary()` reports
/// the handle the frame decodes with.
#[cfg(all(feature = "std", target_has_atomic = "ptr"))]
#[test]
fn force_dict_and_dictionary_cover_these_frames() {
    use crate::decoding::{BlockDecodingStrategy, DictionaryHandle, FrameDecoder};
    let noid = fixture("ModemManager.service.v07.dict-noid.zst");
    let dict =
        DictionaryHandle::from_serialized_or_raw_content(noid.dict.as_deref().unwrap()).unwrap();
    let id = dict.id();
    let mut decoder = FrameDecoder::new();
    decoder.add_dict_handle(dict).unwrap();

    let mut src = &noid.frame[..];
    decoder.reset(&mut src).unwrap();
    assert!(decoder.dictionary().is_none());
    decoder.force_dict(id).unwrap();
    assert_eq!(decoder.dictionary().map(DictionaryHandle::id), Some(id));
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert!(decoder.collect().unwrap() == noid.content);

    // A frame naming the dictionary takes it from the registry.
    let named = fixture("ModemManager.service.v07.dict.zst");
    decoder.reset(&named.frame[..]).unwrap();
    assert_eq!(decoder.dictionary().map(DictionaryHandle::id), Some(id));
}

/// After `decode_all_with_dict_handle` the decoder reports the dictionary the
/// frame decoded with, as it does after an RFC 8878 frame.
#[cfg(feature = "std")]
#[test]
fn a_frame_decoded_whole_keeps_its_dictionary() {
    use crate::decoding::{DictionaryHandle, FrameDecoder};
    let named = fixture("ModemManager.service.v07.dict.zst");
    let dict =
        DictionaryHandle::from_serialized_or_raw_content(named.dict.as_deref().unwrap()).unwrap();
    let mut decoder = FrameDecoder::new();
    let mut out = vec![0u8; named.content.len()];
    decoder
        .decode_all_with_dict_handle(&named.frame, &mut out, &dict)
        .unwrap();
    assert!(out == named.content);
    assert_eq!(
        decoder.dictionary().map(DictionaryHandle::id),
        Some(dict.id())
    );
}

/// The byte-taking entry points accept a dictionary in the v0.5 or v0.6
/// layout, which those formats' command lines train, as libzstd's
/// `ZSTD_decompress_usingDict` does.
#[cfg(feature = "std")]
#[test]
fn byte_entry_points_take_v05_and_v06_dictionaries() {
    use crate::decoding::{FrameDecoder, StreamingDecoder};
    use std::io::Read;
    let mut seen = 0;
    for fixture in fixtures() {
        let Some(dict) = fixture.dict.as_deref() else {
            continue;
        };
        if fixture.version == LegacyVersion::V07 {
            continue;
        }
        seen += 1;
        let mut out = vec![0u8; fixture.content.len()];
        let written = FrameDecoder::new()
            .decode_all_with_dict_bytes(&fixture.frame, &mut out, dict)
            .unwrap_or_else(|err| panic!("{}: {err}", fixture.name));
        assert_eq!(written, fixture.content.len(), "{}", fixture.name);
        assert!(out == fixture.content, "{}", fixture.name);

        let mut streamed = Vec::new();
        StreamingDecoder::new_with_dictionary_bytes(&fixture.frame[..], dict)
            .unwrap_or_else(|refused| panic!("{}: {}", fixture.name, refused.error()))
            .read_to_end(&mut streamed)
            .unwrap();
        assert!(streamed == fixture.content, "{}", fixture.name);
    }
    assert!(seen >= 4);
}

/// A dictionary the decoder keeps for reuse from one kind of frame is still
/// reported for its footprint while a frame of the other kind is current, so
/// an owner counting its handles counts it once, when only they keep it.
#[cfg(feature = "std")]
#[test]
fn dictionaries_kept_across_frame_kinds_are_reported() {
    use crate::decoding::{DictionaryHandle, FrameDecoder};
    let named = fixture("ModemManager.service.v07.dict.zst");
    let dict =
        DictionaryHandle::from_serialized_or_raw_content(named.dict.as_deref().unwrap()).unwrap();
    let rfc = crate::encoding::compress_slice_to_vec(
        b"plain",
        crate::encoding::CompressionLevel::Fastest,
    );
    let footprint = DictionaryHandle::exclusive_heap_size([&dict, &dict.clone()]);
    assert!(footprint > 0);

    // A v0.7 frame with the dictionary, then an RFC 8878 frame without.
    let mut decoder = FrameDecoder::new();
    let mut out = vec![0u8; named.content.len()];
    decoder
        .decode_all_with_dict_handle(&named.frame, &mut out, &dict)
        .unwrap();
    decoder.decode_all(&rfc, &mut out).unwrap();
    assert_eq!(
        DictionaryHandle::exclusive_heap_size(
            core::iter::once(&dict).chain(decoder.dictionaries())
        ),
        footprint
    );
    drop(decoder);

    // An RFC 8878 frame with the dictionary, then a v0.5 frame without.
    let mut compressor =
        crate::encoding::FrameCompressor::new(crate::encoding::CompressionLevel::Fastest);
    compressor
        .set_dictionary_from_bytes(named.dict.as_deref().unwrap())
        .unwrap();
    compressor.set_source(&b"primed"[..]);
    let mut with_dict = Vec::new();
    compressor.set_drain(&mut with_dict);
    compressor.compress();
    drop(compressor);
    let v05 = fixture("abc.txt.v05.l1.zst");
    let mut decoder = FrameDecoder::new();
    decoder
        .decode_all_with_dict_handle(&with_dict, &mut out, &dict)
        .unwrap();
    decoder.decode_all(&v05.frame, &mut out).unwrap();
    assert_eq!(
        DictionaryHandle::exclusive_heap_size(
            core::iter::once(&dict).chain(decoder.dictionaries())
        ),
        footprint
    );
}

/// v0.5 and v0.6 take a dictionary of the RFC 8878 layout whole, header and
/// tables too, as history: a frame matching into that header decodes, on
/// the whole-buffer path and the stream alike, as libzstd decodes it.
#[cfg(feature = "std")]
#[test]
fn a_serialized_dictionary_is_whole_history_to_v05_and_v06() {
    use crate::decoding::{BlockDecodingStrategy, DictionaryHandle, FrameDecoder};
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let raw = std::fs::read(root.join("dict_tests/dictionary")).unwrap();
    let dict = DictionaryHandle::from_serialized_or_raw_content(&raw).unwrap();
    for tag in ["v05", "v06"] {
        let frame =
            std::fs::read(root.join(std::format!("legacy_frames/rfc_dict/dictionary.{tag}.zst")))
                .unwrap();
        let mut out = vec![0u8; raw.len()];
        let written = FrameDecoder::new()
            .decode_all_with_dict_handle(&frame, &mut out, &dict)
            .unwrap_or_else(|err| panic!("{tag}: {err}"));
        assert!(out[..written] == raw[..], "{tag}");

        let mut decoder = FrameDecoder::new();
        let mut src = &frame[..];
        decoder.reset_with_dict_handle(&mut src, &dict).unwrap();
        decoder
            .decode_blocks(&mut src, BlockDecodingStrategy::All)
            .unwrap_or_else(|err| panic!("{tag}: {err}"));
        assert!(decoder.collect().unwrap() == raw, "{tag}");

        // Registered from its bytes and forced by ID, it is whole too.
        let mut decoder = FrameDecoder::new();
        decoder.add_dict_from_bytes(&raw).unwrap();
        let mut src = &frame[..];
        decoder.reset(&mut src).unwrap();
        decoder.force_dict(dict.id()).unwrap();
        decoder
            .decode_blocks(&mut src, BlockDecodingStrategy::All)
            .unwrap_or_else(|err| panic!("{tag} registered: {err}"));
        assert!(decoder.collect().unwrap() == raw, "{tag} registered");
    }
}

/// The header size query measures these frames by their own size fields.
#[test]
fn frame_header_size_measures_these_frames() {
    use crate::decoding::frame_header_size;
    assert_eq!(
        frame_header_size(&[0x25, 0xB5, 0x2F, 0xFD, 0x01]).unwrap(),
        5
    );
    assert_eq!(
        frame_header_size(&[0x26, 0xB5, 0x2F, 0xFD, 0x80]).unwrap(),
        7
    );
    assert_eq!(
        frame_header_size(&[0x27, 0xB5, 0x2F, 0xFD, 0xE3]).unwrap(),
        17
    );
    assert!(frame_header_size(&[0x27, 0xB5, 0x2F, 0xFD]).is_err());
}

/// A reader failing inside a raw or RLE block's body names that block's
/// type, not a compressed block's.
#[cfg(feature = "std")]
#[test]
fn reader_errors_name_the_block_type() {
    use crate::blocks::block::BlockType;
    use crate::decoding::errors::{DecodeBlockContentError, FrameDecoderError};
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    // v0.7, a raw block of five bytes cut after two.
    let frame = [0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00, 0x40, 0, 5, b'a', b'b'];
    let mut decoder = FrameDecoder::new();
    let mut src = &frame[..];
    decoder.reset(&mut src).unwrap();
    let err = decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap_err();
    assert!(
        matches!(
            err,
            FrameDecoderError::FailedToReadBlockBody(DecodeBlockContentError::ReadError {
                step: BlockType::Raw,
                ..
            })
        ),
        "{err:?}"
    );
}

/// Output a caller does not collect stays in the buffer however far past the
/// window it grows, and all of it is handed out once collected.
#[cfg(feature = "std")]
#[test]
fn output_held_back_grows_the_buffer() {
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    let fixture = fixture("z000000x8.v07.l1.zst");
    let mut decoder = FrameDecoder::new();
    let mut src = &fixture.frame[..];
    decoder.reset(&mut src).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    assert!(decoder.collect().unwrap() == fixture.content);
}

/// Damaged frames are refused or decode to some output, but never panic,
/// wherever the damage lands: random bytes overwritten, through every format
/// and both decoding paths.
#[cfg(feature = "std")]
#[test]
fn overwritten_bytes_never_panic() {
    use crate::decoding::FrameDecoder;
    let mut state = 0x2545_F491_4F6C_DD1Du64;
    let mut next = move || {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        state
    };
    for fixture in fixtures().into_iter().filter(|f| f.frame.len() < 16384) {
        let dict = fixture.legacy_dict();
        let header = read_header(&fixture.frame).unwrap().size;
        for _ in 0..64 {
            let mut frame = fixture.frame.clone();
            for _ in 0..(next() % 4) + 1 {
                let at = header + (next() as usize) % (frame.len() - header);
                frame[at] = next() as u8;
            }
            let _whole = decode_verified(&frame, dict).is_ok();
            let mut decoder = FrameDecoder::new();
            let mut target = vec![0u8; 4096];
            let mut src = &frame[..];
            while let Ok((read, written)) = decoder.decode_from_to(src, &mut target) {
                if read == 0 && written == 0 {
                    break;
                }
                src = &src[read..];
            }
        }
    }
}

/// An RLE block repeats its byte in v0.7; v0.5 and v0.6 reserve the type,
/// and their decoders refuse it (`ZSTDv0{5,6}_decompressFrame`).
#[test]
fn rle_blocks_repeat_their_byte_in_v07_only() {
    for magic in [0x25u8, 0x26, 0x27] {
        let mut frame = vec![magic, 0xB5, 0x2F, 0xFD, 0x00];
        if magic == 0x27 {
            frame.push(0x00);
        }
        frame.extend_from_slice(&[0x80, 0, 5, b'z', 0xC0, 0, 0]);
        let decoded = decode_to_vec(&frame, LegacyDict::None);
        if magic == 0x27 {
            let (decoded, consumed) = decoded.unwrap();
            assert_eq!(decoded, b"zzzzz");
            assert_eq!(consumed, frame.len());
        } else {
            assert!(
                matches!(decoded, Err(Error::Corrupted { .. })),
                "{magic:#x}: {decoded:?}"
            );
        }
    }
}

/// A compressed block may not hold past the largest block size, whatever
/// its header claims; a stored one runs to its size field, as
/// `ZSTDv07_generateNxBytes` fills an RLE block of any size the output takes.
#[test]
fn only_compressed_blocks_stop_at_the_largest_block_size() {
    let size = BLOCK_SIZE_MAX + 1;
    let header = |kind: u8| [kind | (size >> 16) as u8, (size >> 8) as u8, size as u8];
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    frame.extend_from_slice(&header(0x80));
    frame.push(b'z');
    frame.extend_from_slice(&[0xC0, 0, 0]);
    let (out, _) = decode_to_vec(&frame, LegacyDict::None).unwrap();
    assert!(out.len() == size && out.iter().all(|&b| b == b'z'));

    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    frame.extend_from_slice(&header(0x00));
    frame.resize(frame.len() + size, 0);
    frame.extend_from_slice(&[0xC0, 0, 0]);
    assert!(matches!(
        decode_to_vec(&frame, LegacyDict::None),
        Err(Error::Corrupted { .. })
    ));
}

/// The declared content size does not bound the output: the v0.6.2 command
/// line declares its first chunk's size, and the blocks are what decode.
#[cfg(feature = "std")]
#[test]
fn the_declared_content_size_is_not_enforced() {
    // v0.6 with a one-byte content size of 4 and a raw block of 5.
    let frame = [
        0x26, 0xB5, 0x2F, 0xFD, 0x40, 4, 0x40, 0, 5, b'z', b'z', b'z', b'z', b'z', 0xC0, 0, 0,
    ];
    assert_eq!(declared_content_size(&frame), Some(4));
    assert_eq!(
        decode_to_vec(&frame, LegacyDict::None).unwrap(),
        (b"zzzzz".to_vec(), frame.len())
    );
    // A v0.6 archive from that command line, past 128 KiB, declares 128 KiB.
    let fixture = fixtures()
        .into_iter()
        .find(|f| f.name == "z000000.v06.l1.zst")
        .unwrap();
    assert_eq!(declared_content_size(&fixture.frame), Some(128 * 1024));
    assert_eq!(fixture.content.len(), 224_787);
}

/// A header field the formats refuse carries libzstd's code for the path:
/// decoded whole, v0.6 and v0.7 report it as corruption, as their one-shot
/// decoders wrap every header error (`ZSTDv0{6,7}_decompressFrame`); through
/// a stream, as their buffered decoders do, an unsupported parameter. v0.5
/// reports its own code on both paths.
#[cfg(feature = "std")]
#[test]
fn refused_header_fields_carry_the_code_of_their_path() {
    use crate::decoding::FrameDecoder;
    use crate::decoding::errors::ErrorCode;
    let end = [0xC0, 0, 0];
    let frame = |header: &[u8]| {
        let mut frame = header.to_vec();
        frame.extend_from_slice(&end);
        frame
    };
    let cases = [
        // v0.7 reserved bit 3.
        (
            frame(&[0x27, 0xB5, 0x2F, 0xFD, 0x08, 0x00]),
            ErrorCode::CorruptionDetected,
        ),
        // v0.7 window past the format's largest.
        (
            frame(&[0x27, 0xB5, 0x2F, 0xFD, 0x00, 0xF8]),
            ErrorCode::CorruptionDetected,
        ),
        // v0.6 reserved bit 5.
        (
            frame(&[0x26, 0xB5, 0x2F, 0xFD, 0x20]),
            ErrorCode::CorruptionDetected,
        ),
        // v0.5 reserved descriptor bits.
        (
            frame(&[0x25, 0xB5, 0x2F, 0xFD, 0x10]),
            ErrorCode::FrameParameterUnsupported,
        ),
    ];
    for (frame, whole) in cases {
        let mut out = [0u8; 8];
        let err = FrameDecoder::new()
            .decode_all(&frame, &mut out)
            .unwrap_err();
        assert_eq!(err.code(), whole, "{frame:02x?}");
        let err = FrameDecoder::new().reset(&frame[..]).unwrap_err();
        assert_eq!(
            err.code(),
            ErrorCode::FrameParameterUnsupported,
            "{frame:02x?}"
        );
    }
}

/// The size queries refuse a block the decoder refuses from its header, as
/// they refuse an RFC 8878 one: a compressed block past 128 KiB, and an RLE
/// block in v0.5 or v0.6, which reserve the type.
#[test]
fn size_queries_refuse_blocks_the_decoder_refuses() {
    use crate::decoding::{FrameSizeError, find_frame_compressed_size, frame_decompressed_bound};
    let oversized = one_block_frame(LegacyVersion::V07, &vec![0u8; BLOCK_SIZE_MAX + 1]);
    assert!(matches!(
        find_frame_compressed_size(&oversized),
        Err(FrameSizeError::OversizedBlock)
    ));
    assert!(matches!(
        frame_decompressed_bound(&oversized),
        Err(FrameSizeError::OversizedBlock)
    ));
    let mut rle = vec![
        0x26, 0xB5, 0x2F, 0xFD, 0x00, 0x80, 0x00, 0x04, b'z', 0xC0, 0, 0,
    ];
    assert!(matches!(
        find_frame_compressed_size(&rle),
        Err(FrameSizeError::ReservedBlock)
    ));
    // The same block is a run in v0.7.
    rle.splice(..5, [0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00]);
    assert_eq!(find_frame_compressed_size(&rle).unwrap(), rle.len());
}

/// A stored block past 128 KiB that arrives while the segment is still short
/// of the window grows the buffer by that block, not by doubling it: the
/// stream holds at most its window and one block of any type.
#[test]
fn a_large_stored_block_grows_the_stream_by_itself() {
    // v0.7 with a 1 MiB window.
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x50];
    let mut content = Vec::new();
    for n in 0..7u8 {
        frame.extend_from_slice(&[0x40 | 0x02, 0x00, 0x00]);
        let block = vec![n; 128 * 1024];
        frame.extend_from_slice(&block);
        content.extend_from_slice(&block);
    }
    let big: Vec<u8> = (0..500_000u32).map(|n| (n % 253) as u8).collect();
    frame.extend_from_slice(&[0x40 | 0x07, 0xA1, 0x20]);
    frame.extend_from_slice(&big);
    content.extend_from_slice(&big);
    frame.extend_from_slice(&[0xC0, 0x00, 0x00]);

    let header = read_header(&frame).unwrap();
    let mut stream = LegacyStream::new();
    stream.start(header, None, FrameOptions::default()).unwrap();
    let mut out = vec![0u8; content.len()];
    let (mut read, mut written) = (header.size, 0);
    while !stream.is_finished() {
        let (r, w) = stream.decode(&frame[read..], &mut out[written..]).unwrap();
        assert!(r > 0 || w > 0);
        read += r;
        written += w;
    }
    assert_eq!(written, content.len());
    assert!(out == content);
    assert!(
        stream.buf.capacity() <= (1 << 20) + STORED_BLOCK_MAX,
        "{}",
        stream.buf.capacity()
    );
}

/// A frame of `version` holding one compressed block, `body`, then an end.
fn one_block_frame(version: LegacyVersion, body: &[u8]) -> Vec<u8> {
    let mut frame = match version {
        LegacyVersion::V05 => vec![0x25, 0xB5, 0x2F, 0xFD, 0x00],
        LegacyVersion::V06 => vec![0x26, 0xB5, 0x2F, 0xFD, 0x00],
        LegacyVersion::V07 => vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00],
    };
    let n = body.len();
    frame.extend_from_slice(&[(n >> 16) as u8, (n >> 8) as u8, n as u8]);
    frame.extend_from_slice(body);
    frame.extend_from_slice(&[0xC0, 0, 0]);
    frame
}

const VERSIONS: [LegacyVersion; 3] = [LegacyVersion::V05, LegacyVersion::V06, LegacyVersion::V07];

/// A compressed block may hold literals alone, no sequence after them, with
/// a one- or two-byte raw literal header.
#[test]
fn a_block_of_literals_alone_decodes() {
    for version in VERSIONS {
        for body in [
            &[0x83, b'a', b'b', b'c', 0x00][..],
            &[0xA0, 0x03, b'a', b'b', b'c', 0x00][..],
        ] {
            let frame = one_block_frame(version, body);
            assert_eq!(
                decode_to_vec(&frame, LegacyDict::None).unwrap(),
                (b"abc".to_vec(), frame.len()),
                "{version:?} {body:02x?}"
            );
        }
    }
}

/// The four-stream literal forms v0.5 and v0.6 decode without a table: a
/// one-byte section is a run of it, and in v0.6 a section as long as its
/// content is the content. v0.7 refuses both.
#[test]
fn degenerate_literal_sections_decode_in_older_formats() {
    // Ten literals in one compressed byte, then no sequences.
    let run = [0x20, 0x02, 0x80, 0x01, b'x', 0x00];
    // Three literals in three bytes.
    let stored = [0x20, 0x00, 0xC0, 0x03, b'a', b'b', b'c', 0x00];
    for version in [LegacyVersion::V05, LegacyVersion::V06] {
        let frame = one_block_frame(version, &run);
        assert_eq!(
            decode_to_vec(&frame, LegacyDict::None).unwrap().0,
            vec![b'x'; 10],
            "{version:?}"
        );
    }
    let frame = one_block_frame(LegacyVersion::V06, &stored);
    assert_eq!(
        decode_to_vec(&frame, LegacyDict::None).unwrap().0,
        b"abc".to_vec()
    );
    assert!(
        decode_to_vec(
            &one_block_frame(LegacyVersion::V05, &stored),
            LegacyDict::None
        )
        .is_err()
    );
    for body in [&run[..], &stored[..]] {
        let frame = one_block_frame(LegacyVersion::V07, body);
        assert!(decode_to_vec(&frame, LegacyDict::None).is_err());
    }
}

/// A Huffman literal section that holds only its table is refused, as is a
/// single stream that does not decode to its literals.
#[test]
fn single_stream_literals_need_their_stream() {
    // Single stream, 4 literals: a two-weight table and nothing after it.
    let table_only = [0x10, 0x10, 0x02, 0x81, 0x11, 0x00];
    // The same with one stream byte that holds no bits.
    let empty_stream = [0x10, 0x10, 0x03, 0x81, 0x11, 0x01, 0x00];
    for version in VERSIONS {
        for body in [&table_only[..], &empty_stream[..]] {
            let frame = one_block_frame(version, body);
            assert!(
                decode_to_vec(&frame, LegacyDict::None).is_err(),
                "{version:?} {body:02x?}"
            );
        }
    }
}

/// A sequence section is refused when it ends inside its header, or repeats
/// a table no block or dictionary has sent.
#[test]
fn bad_sequence_headers_are_refused() {
    // One sequence, then too few bytes for the modes and tables.
    let cut = [0x80, 0x01, 0x00, 0x00];
    for version in [LegacyVersion::V06, LegacyVersion::V07] {
        assert!(matches!(
            decode_to_vec(&one_block_frame(version, &cut), LegacyDict::None),
            Err(Error::Truncated)
        ));
    }
    // Literal lengths in repeat mode, before any table.
    let repeat_v06 = [0x80, 0x01, 0x80, 0x00, 0x00, 0x00];
    let repeat_v05 = [0x80, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00];
    for (version, body) in [
        (LegacyVersion::V05, &repeat_v05[..]),
        (LegacyVersion::V06, &repeat_v06[..]),
        (LegacyVersion::V07, &repeat_v06[..]),
    ] {
        assert!(matches!(
            decode_to_vec(&one_block_frame(version, body), LegacyDict::None),
            Err(Error::Corrupted { .. })
        ));
    }
    // v0.5: literal lengths described (three bytes), then an offset run
    // whose symbol is missing its following byte.
    let rle_cut = [0x80, 0x01, 0xD0, 0x00, 0x10, 0xF8, 0x01, 0x05];
    assert!(matches!(
        decode_to_vec(
            &one_block_frame(LegacyVersion::V05, &rle_cut),
            LegacyDict::None
        ),
        Err(Error::Truncated)
    ));
}

/// v0.5 run tables: the offset symbol is masked to the field, and a literal
/// length past the largest symbol reads a 16-bit value from the dumps,
/// halved.
#[test]
fn v05_run_tables_and_long_dumps_decode() {
    let mut body = vec![0x88];
    body.extend_from_slice(b"abcdefgh");
    // One sequence; all three fields a run; three dump bytes.
    body.extend_from_slice(&[0x01, 0x54, 0x03, 0xFF, 0x10, 0x00]);
    // Literal length 63 (from the dumps: 16 / 2), offset code 0x21 masked
    // to 1, match length 0 (+4); an empty bitstream.
    body.extend_from_slice(&[0x3F, 0x21, 0x00, 0x80]);
    let frame = one_block_frame(LegacyVersion::V05, &body);
    assert_eq!(
        decode_to_vec(&frame, LegacyDict::None).unwrap().0,
        b"abcdefghhhhh".to_vec()
    );

    // A 255 dump byte with no two bytes after it leaves the length at the
    // field's largest, 63.
    let literals: Vec<u8> = (0..63u8).collect();
    let mut body = vec![0xA0, 63];
    body.extend_from_slice(&literals);
    body.extend_from_slice(&[0x01, 0x54, 0x01, 0xFF, 0x3F, 0x21, 0x00, 0x80]);
    let frame = one_block_frame(LegacyVersion::V05, &body);
    let mut expected = literals.clone();
    expected.extend_from_slice(&[62; 4]);
    assert_eq!(decode_to_vec(&frame, LegacyDict::None).unwrap().0, expected);
}

/// A compressed block body of the full 128 KiB is refused: the formats hold
/// one to less than that (`ZSTDv0{5,6,7}_decompressBlock_internal`).
#[test]
fn a_full_size_compressed_block_is_refused() {
    let body = vec![0u8; BLOCK_SIZE_MAX];
    for version in VERSIONS {
        assert!(matches!(
            decode_to_vec(&one_block_frame(version, &body), LegacyDict::None),
            Err(Error::Corrupted { .. })
        ));
    }
}

/// A v0.5 or v0.6 dictionary whose offset table is larger than its format's
/// is refused as a corrupted dictionary.
#[test]
fn a_dictionary_table_past_its_format_is_refused() {
    // Log 10, one symbol taking the whole table.
    let offsets = [0xF5, 0x7F, 0x00, 0x00];
    for (version, magic) in [(LegacyVersion::V05, 0x35), (LegacyVersion::V06, 0x36)] {
        let mut bytes = vec![magic, 0xA4, 0x30, 0xEC, 0x81, 0x11];
        bytes.extend_from_slice(&offsets);
        bytes.extend_from_slice(&[0; 32]);
        let dict = crate::decoding::Dictionary::from_raw_content(0, bytes).unwrap();
        let frame = one_block_frame(version, &[0x83, b'a', b'b', b'c', 0x00]);
        assert!(matches!(
            decode_to_vec(
                &frame,
                LegacyDict::Parsed {
                    dict: &dict,
                    header: &[]
                }
            ),
            Err(Error::DictionaryCorrupted)
        ));
    }
}

/// A parsed dictionary a v0.7 frame cannot use, its offset table larger
/// than the format's or a repeat offset of 0, is refused when the frame
/// starts, on the whole-buffer path and the stream alike.
#[cfg(feature = "std")]
#[test]
fn a_v07_frame_refuses_a_dictionary_it_cannot_use() {
    use crate::decoding::errors::FrameDecoderError;
    use crate::decoding::{Dictionary, DictionaryHandle, FrameDecoder};
    let raw = include_bytes!("../../../dict_tests/dictionary");
    let frame = one_block_frame(LegacyVersion::V07, &[0x83, b'a', b'b', b'c', 0x00]);
    let mut zero_offset = Dictionary::decode_dict(raw).unwrap();
    zero_offset.offset_hist[1] = 0;
    let mut wide_offsets = Dictionary::decode_dict(raw).unwrap();
    wide_offsets.fse.offsets.accuracy_log = 9;
    for dict in [zero_offset, wide_offsets] {
        let handle = DictionaryHandle::from_dictionary(dict);
        let mut out = [0u8; 8];
        // A zero repeat offset is refused by any reset that takes the
        // dictionary as given, before the frame looks at it.
        let refused = |result| {
            matches!(
                result,
                Err(FrameDecoderError::LegacyFrame(Error::DictionaryCorrupted))
                    | Err(FrameDecoderError::DictionaryDecodeError(_))
            )
        };
        let mut decoder = FrameDecoder::new();
        assert!(refused(
            decoder
                .decode_all_with_dict_handle(&frame, &mut out, &handle)
                .map(|_| ())
        ));
        assert!(refused(decoder.reset_with_dict_handle(&frame[..], &handle)));
    }
}

/// The step interface on one of these frames: a byte budget stops after
/// the block that meets it, a run block is read from the source, and once
/// the frame is done it wants no more input; its output goes to a writer
/// or a reader.
#[cfg(feature = "std")]
#[test]
fn the_step_interface_covers_these_frames() {
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    use std::io::Read;
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    frame.extend_from_slice(&[0x80, 0x00, 0x05, b'z']);
    frame.extend_from_slice(&[0x40, 0x00, 0x02, b'a', b'b']);
    frame.extend_from_slice(&[0xC0, 0x00, 0x00]);

    let mut decoder = FrameDecoder::new();
    let mut src = &frame[..];
    decoder.reset(&mut src).unwrap();
    assert!(
        !decoder
            .decode_blocks(&mut src, BlockDecodingStrategy::UptoBytes(1))
            .unwrap()
    );
    assert_eq!(decoder.can_collect(), 5);
    assert!(
        decoder
            .decode_blocks(&mut src, BlockDecodingStrategy::All)
            .unwrap()
    );
    assert_eq!(decoder.input_needed(&[]), 0);
    let mut written = Vec::new();
    assert_eq!(decoder.collect_to_writer(&mut written).unwrap(), 7);
    assert_eq!(written, b"zzzzzab");

    let mut decoder = FrameDecoder::new();
    let mut src = &frame[..];
    decoder.reset(&mut src).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    let mut read = [0u8; 16];
    assert_eq!(decoder.read(&mut read).unwrap(), 7);
    assert_eq!(&read[..7], b"zzzzzab");
}

/// A damaged block after output already handed to the reader is reported by
/// the next read, not by the one that delivered: `Read` may not return an
/// error for a call that filled part of its buffer. Covers output left from
/// an earlier read and output decoded in the same read.
#[cfg(feature = "std")]
#[test]
fn a_damaged_block_after_delivered_output_waits_for_the_next_read() {
    use crate::decoding::StreamingDecoder;
    use std::io::Read;
    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    frame.extend_from_slice(&[0x40, 0x00, 0x08]);
    frame.extend_from_slice(b"abcdefgh");
    // Three literals declared, one present.
    frame.extend_from_slice(&[0x00, 0x00, 0x02, 0x83, b'a']);
    frame.extend_from_slice(&[0xC0, 0x00, 0x00]);

    let mut decoder = StreamingDecoder::new(&frame[..]);
    let mut buf = [0u8; 64];
    assert_eq!(decoder.read(&mut buf).unwrap(), 8);
    assert_eq!(&buf[..8], b"abcdefgh");
    assert!(decoder.read(&mut buf).is_err());

    let mut decoder = StreamingDecoder::new(&frame[..]);
    assert_eq!(decoder.read(&mut buf[..3]).unwrap(), 3);
    assert_eq!(decoder.read(&mut buf).unwrap(), 5);
    assert_eq!(&buf[..5], b"defgh");
    assert!(decoder.read(&mut buf).is_err());
}

/// A writer that takes part of the output and then fails keeps that part:
/// the next collection starts after it, as for RFC 8878 frames.
#[cfg(feature = "std")]
#[test]
fn collect_to_writer_keeps_what_a_failing_writer_took() {
    use crate::decoding::{BlockDecodingStrategy, FrameDecoder};
    use std::io::{ErrorKind, Write};

    /// Takes `room` bytes, then would block.
    struct Partial {
        took: Vec<u8>,
        room: usize,
    }
    impl Write for Partial {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            if self.room == 0 {
                return Err(ErrorKind::WouldBlock.into());
            }
            let n = buf.len().min(self.room);
            self.took.extend_from_slice(&buf[..n]);
            self.room -= n;
            Ok(n)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    let mut frame = vec![0x27, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
    frame.extend_from_slice(&[0x40, 0x00, 0x08]);
    frame.extend_from_slice(b"abcdefgh");
    frame.extend_from_slice(&[0xC0, 0x00, 0x00]);
    let mut decoder = FrameDecoder::new();
    let mut src = &frame[..];
    decoder.reset(&mut src).unwrap();
    decoder
        .decode_blocks(&mut src, BlockDecodingStrategy::All)
        .unwrap();
    let mut sink = Partial {
        took: Vec::new(),
        room: 3,
    };
    assert!(decoder.collect_to_writer(&mut sink).is_err());
    assert_eq!(sink.took, b"abc");
    assert_eq!(decoder.can_collect(), 5);
    sink.room = 16;
    assert_eq!(decoder.collect_to_writer(&mut sink).unwrap(), 5);
    assert_eq!(sink.took, b"abcdefgh");
}