1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
use std::convert::TryInto;
use std::error;
use std::fmt;
use std::io;
use std::{borrow::Cow, cmp::min};

use crc32fast::Hasher as Crc32;

use super::zlib::ZlibStream;
use crate::chunk::{self, ChunkType, IDAT, IEND, IHDR};
use crate::common::{
    AnimationControl, BitDepth, BlendOp, ColorType, ContentLightLevelInfo, DisposeOp, FrameControl,
    Info, MasteringDisplayColorVolume, ParameterError, ParameterErrorKind, PixelDimensions,
    ScaledFloat, SourceChromaticities, Unit,
};
use crate::text_metadata::{ITXtChunk, TEXtChunk, TextDecodingError, ZTXtChunk};
use crate::traits::ReadBytesExt;
use crate::{CodingIndependentCodePoints, Limits};

/// TODO check if these size are reasonable
pub const CHUNK_BUFFER_SIZE: usize = 32 * 1024;

/// Determines if checksum checks should be disabled globally.
///
/// This is used only in fuzzing. `afl` automatically adds `--cfg fuzzing` to RUSTFLAGS which can
/// be used to detect that build.
const CHECKSUM_DISABLED: bool = cfg!(fuzzing);

/// Kind of `u32` value that is being read via `State::U32`.
#[derive(Debug)]
enum U32ValueKind {
    /// First 4 bytes of the PNG signature - see
    /// http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#PNG-file-signature
    Signature1stU32,
    /// Second 4 bytes of the PNG signature - see
    /// http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#PNG-file-signature
    Signature2ndU32,
    /// Chunk length - see
    /// http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#Chunk-layout
    Length,
    /// Chunk type - see
    /// http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#Chunk-layout
    Type { length: u32 },
    /// Chunk checksum - see
    /// http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#Chunk-layout
    Crc(ChunkType),
    /// Sequence number from an `fdAT` chunk - see
    /// https://wiki.mozilla.org/APNG_Specification#.60fdAT.60:_The_Frame_Data_Chunk
    ApngSequenceNumber,
}

#[derive(Debug)]
enum State {
    /// In this state we are reading a u32 value from external input.  We start with
    /// `accumulated_count` set to `0`. After reading or accumulating the required 4 bytes we will
    /// call `parse_32` which will then move onto the next state.
    U32 {
        kind: U32ValueKind,
        bytes: [u8; 4],
        accumulated_count: usize,
    },
    /// In this state we are reading chunk data from external input, and appending it to
    /// `ChunkState::raw_bytes`.
    ReadChunkData(ChunkType),
    /// In this state we check if all chunk data has been already read into `ChunkState::raw_bytes`
    /// and if so then we parse the chunk.  Otherwise, we go back to the `ReadChunkData` state.
    ParseChunkData(ChunkType),
    /// In this state we are reading image data from external input and feeding it directly into
    /// `StreamingDecoder::inflater`.
    ImageData(ChunkType),
}

impl State {
    fn new_u32(kind: U32ValueKind) -> Self {
        Self::U32 {
            kind,
            bytes: [0; 4],
            accumulated_count: 0,
        }
    }
}

#[derive(Debug)]
/// Result of the decoding process
pub enum Decoded {
    /// Nothing decoded yet
    Nothing,
    Header(u32, u32, BitDepth, ColorType, bool),
    ChunkBegin(u32, ChunkType),
    ChunkComplete(u32, ChunkType),
    PixelDimensions(PixelDimensions),
    AnimationControl(AnimationControl),
    FrameControl(FrameControl),
    /// Decoded raw image data.
    ImageData,
    /// The last of a consecutive chunk of IDAT was done.
    /// This is distinct from ChunkComplete which only marks that some IDAT chunk was completed but
    /// not that no additional IDAT chunk follows.
    ImageDataFlushed,
    PartialChunk(ChunkType),
    ImageEnd,
}

/// Any kind of error during PNG decoding.
///
/// This enumeration provides a very rough analysis on the origin of the failure. That is, each
/// variant corresponds to one kind of actor causing the error. It should not be understood as a
/// direct blame but can inform the search for a root cause or if such a search is required.
#[derive(Debug)]
pub enum DecodingError {
    /// An error in IO of the underlying reader.
    ///
    /// Note that some IO errors may be recoverable - decoding may be retried after the
    /// error is resolved.  For example, decoding from a slow stream of data (e.g. decoding from a
    /// network stream) may occasionally result in [std::io::ErrorKind::UnexpectedEof] kind of
    /// error, but decoding can resume when more data becomes available.
    IoError(io::Error),
    /// The input image was not a valid PNG.
    ///
    /// There isn't a lot that can be done here, except if the program itself was responsible for
    /// creating this image then investigate the generator. This is internally implemented with a
    /// large Enum. If You are interested in accessing some of the more exact information on the
    /// variant then we can discuss in an issue.
    Format(FormatError),
    /// An interface was used incorrectly.
    ///
    /// This is used in cases where it's expected that the programmer might trip up and stability
    /// could be affected. For example when:
    ///
    /// * The decoder is polled for more animation frames despite being done (or not being animated
    ///   in the first place).
    /// * The output buffer does not have the required size.
    ///
    /// As a rough guideline for introducing new variants parts of the requirements are dynamically
    /// derived from the (untrusted) input data while the other half is from the caller. In the
    /// above cases the number of frames respectively the size is determined by the file while the
    /// number of calls
    ///
    /// If you're an application you might want to signal that a bug report is appreciated.
    Parameter(ParameterError),
    /// The image would have required exceeding the limits configured with the decoder.
    ///
    /// Note that Your allocations, e.g. when reading into a pre-allocated buffer, is __NOT__
    /// considered part of the limits. Nevertheless, required intermediate buffers such as for
    /// singular lines is checked against the limit.
    ///
    /// Note that this is a best-effort basis.
    LimitsExceeded,
}

#[derive(Debug)]
pub struct FormatError {
    inner: FormatErrorInner,
}

#[derive(Debug)]
pub(crate) enum FormatErrorInner {
    /// Bad framing.
    CrcMismatch {
        /// Stored CRC32 value
        crc_val: u32,
        /// Calculated CRC32 sum
        crc_sum: u32,
        /// The chunk type that has the CRC mismatch.
        chunk: ChunkType,
    },
    /// Not a PNG, the magic signature is missing.
    InvalidSignature,
    // Errors of chunk level ordering, missing etc.
    /// Fctl must occur if an animated chunk occurs.
    MissingFctl,
    /// Image data that was indicated in IHDR or acTL is missing.
    MissingImageData,
    /// 4.3., Must be first.
    ChunkBeforeIhdr {
        kind: ChunkType,
    },
    /// 4.3., some chunks must be before IDAT.
    AfterIdat {
        kind: ChunkType,
    },
    // 4.3., Some chunks must be after PLTE.
    BeforePlte {
        kind: ChunkType,
    },
    /// 4.3., some chunks must be before PLTE.
    AfterPlte {
        kind: ChunkType,
    },
    /// 4.3., some chunks must be between PLTE and IDAT.
    OutsidePlteIdat {
        kind: ChunkType,
    },
    /// 4.3., some chunks must be unique.
    DuplicateChunk {
        kind: ChunkType,
    },
    /// Specifically for fdat there is an embedded sequence number for chunks.
    ApngOrder {
        /// The sequence number in the chunk.
        present: u32,
        /// The one that should have been present.
        expected: u32,
    },
    // Errors specific to particular chunk data to be validated.
    /// The palette did not even contain a single pixel data.
    ShortPalette {
        expected: usize,
        len: usize,
    },
    /// sBIT chunk size based on color type.
    InvalidSbitChunkSize {
        color_type: ColorType,
        expected: usize,
        len: usize,
    },
    InvalidSbit {
        sample_depth: BitDepth,
        sbit: u8,
    },
    /// A palletized image did not have a palette.
    PaletteRequired,
    /// The color-depth combination is not valid according to Table 11.1.
    InvalidColorBitDepth {
        color_type: ColorType,
        bit_depth: BitDepth,
    },
    ColorWithBadTrns(ColorType),
    /// The image width or height is zero.
    InvalidDimensions,
    InvalidBitDepth(u8),
    InvalidColorType(u8),
    InvalidDisposeOp(u8),
    InvalidBlendOp(u8),
    InvalidUnit(u8),
    /// The rendering intent of the sRGB chunk is invalid.
    InvalidSrgbRenderingIntent(u8),
    UnknownCompressionMethod(u8),
    UnknownFilterMethod(u8),
    UnknownInterlaceMethod(u8),
    /// The subframe is not in bounds of the image.
    /// TODO: fields with relevant data.
    BadSubFrameBounds {},
    // Errors specific to the IDAT/fdAT chunks.
    /// The compression of the data stream was faulty.
    CorruptFlateStream {
        err: fdeflate::DecompressionError,
    },
    /// The image data chunk was too short for the expected pixel count.
    NoMoreImageData,
    /// Bad text encoding
    BadTextEncoding(TextDecodingError),
    /// fdAT shorter than 4 bytes
    FdatShorterThanFourBytes,
    /// "11.2.4 IDAT Image data" section of the PNG spec says: There may be multiple IDAT chunks;
    /// if so, they shall appear consecutively with no other intervening chunks.
    /// `UnexpectedRestartOfDataChunkSequence{kind: IDAT}` indicates that there were "intervening
    /// chunks".
    ///
    /// The APNG spec doesn't directly describe an error similar to `CantInterleaveIdatChunks`,
    /// but we require that a new sequence of consecutive `fdAT` chunks cannot appear unless we've
    /// seen an `fcTL` chunk.
    UnexpectedRestartOfDataChunkSequence {
        kind: ChunkType,
    },
    /// Failure to parse a chunk, because the chunk didn't contain enough bytes.
    ChunkTooShort {
        kind: ChunkType,
    },
}

impl error::Error for DecodingError {
    fn cause(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            DecodingError::IoError(err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for DecodingError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use self::DecodingError::*;
        match self {
            IoError(err) => write!(fmt, "{}", err),
            Parameter(desc) => write!(fmt, "{}", &desc),
            Format(desc) => write!(fmt, "{}", desc),
            LimitsExceeded => write!(fmt, "limits are exceeded"),
        }
    }
}

impl fmt::Display for FormatError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        use FormatErrorInner::*;
        match &self.inner {
            CrcMismatch {
                crc_val,
                crc_sum,
                chunk,
                ..
            } => write!(
                fmt,
                "CRC error: expected 0x{:x} have 0x{:x} while decoding {:?} chunk.",
                crc_val, crc_sum, chunk
            ),
            MissingFctl => write!(fmt, "fcTL chunk missing before fdAT chunk."),
            MissingImageData => write!(fmt, "IDAT or fdAT chunk is missing."),
            ChunkBeforeIhdr { kind } => write!(fmt, "{:?} chunk appeared before IHDR chunk", kind),
            AfterIdat { kind } => write!(fmt, "Chunk {:?} is invalid after IDAT chunk.", kind),
            BeforePlte { kind } => write!(fmt, "Chunk {:?} is invalid before PLTE chunk.", kind),
            AfterPlte { kind } => write!(fmt, "Chunk {:?} is invalid after PLTE chunk.", kind),
            OutsidePlteIdat { kind } => write!(
                fmt,
                "Chunk {:?} must appear between PLTE and IDAT chunks.",
                kind
            ),
            DuplicateChunk { kind } => write!(fmt, "Chunk {:?} must appear at most once.", kind),
            ApngOrder { present, expected } => write!(
                fmt,
                "Sequence is not in order, expected #{} got #{}.",
                expected, present,
            ),
            ShortPalette { expected, len } => write!(
                fmt,
                "Not enough palette entries, expect {} got {}.",
                expected, len
            ),
            InvalidSbitChunkSize {color_type, expected, len} => write!(
                fmt,
                "The size of the sBIT chunk should be {} byte(s), but {} byte(s) were provided for the {:?} color type.",
                expected, len, color_type
            ),
            InvalidSbit {sample_depth, sbit} => write!(
                fmt,
                "Invalid sBIT value {}. It must be greater than zero and less than the sample depth {:?}.",
                sbit, sample_depth
            ),
            PaletteRequired => write!(fmt, "Missing palette of indexed image."),
            InvalidDimensions => write!(fmt, "Invalid image dimensions"),
            InvalidColorBitDepth {
                color_type,
                bit_depth,
            } => write!(
                fmt,
                "Invalid color/depth combination in header: {:?}/{:?}",
                color_type, bit_depth,
            ),
            ColorWithBadTrns(color_type) => write!(
                fmt,
                "Transparency chunk found for color type {:?}.",
                color_type
            ),
            InvalidBitDepth(nr) => write!(fmt, "Invalid bit depth {}.", nr),
            InvalidColorType(nr) => write!(fmt, "Invalid color type {}.", nr),
            InvalidDisposeOp(nr) => write!(fmt, "Invalid dispose op {}.", nr),
            InvalidBlendOp(nr) => write!(fmt, "Invalid blend op {}.", nr),
            InvalidUnit(nr) => write!(fmt, "Invalid physical pixel size unit {}.", nr),
            InvalidSrgbRenderingIntent(nr) => write!(fmt, "Invalid sRGB rendering intent {}.", nr),
            UnknownCompressionMethod(nr) => write!(fmt, "Unknown compression method {}.", nr),
            UnknownFilterMethod(nr) => write!(fmt, "Unknown filter method {}.", nr),
            UnknownInterlaceMethod(nr) => write!(fmt, "Unknown interlace method {}.", nr),
            BadSubFrameBounds {} => write!(fmt, "Sub frame is out-of-bounds."),
            InvalidSignature => write!(fmt, "Invalid PNG signature."),
            NoMoreImageData => write!(
                fmt,
                "IDAT or fDAT chunk does not have enough data for image."
            ),
            CorruptFlateStream { err } => {
                write!(fmt, "Corrupt deflate stream. ")?;
                write!(fmt, "{:?}", err)
            }
            // TODO: Wrap more info in the enum variant
            BadTextEncoding(tde) => {
                match tde {
                    TextDecodingError::Unrepresentable => {
                        write!(fmt, "Unrepresentable data in tEXt chunk.")
                    }
                    TextDecodingError::InvalidKeywordSize => {
                        write!(fmt, "Keyword empty or longer than 79 bytes.")
                    }
                    TextDecodingError::MissingNullSeparator => {
                        write!(fmt, "No null separator in tEXt chunk.")
                    }
                    TextDecodingError::InflationError => {
                        write!(fmt, "Invalid compressed text data.")
                    }
                    TextDecodingError::OutOfDecompressionSpace => {
                        write!(fmt, "Out of decompression space. Try with a larger limit.")
                    }
                    TextDecodingError::InvalidCompressionMethod => {
                        write!(fmt, "Using an unrecognized byte as compression method.")
                    }
                    TextDecodingError::InvalidCompressionFlag => {
                        write!(fmt, "Using a flag that is not 0 or 255 as a compression flag for iTXt chunk.")
                    }
                    TextDecodingError::MissingCompressionFlag => {
                        write!(fmt, "No compression flag in the iTXt chunk.")
                    }
                }
            }
            FdatShorterThanFourBytes => write!(fmt, "fdAT chunk shorter than 4 bytes"),
            UnexpectedRestartOfDataChunkSequence { kind } => {
                write!(fmt, "Unexpected restart of {:?} chunk sequence", kind)
            }
            ChunkTooShort { kind } => {
                write!(fmt, "Chunk is too short: {:?}", kind)
            }
        }
    }
}

impl From<io::Error> for DecodingError {
    fn from(err: io::Error) -> DecodingError {
        DecodingError::IoError(err)
    }
}

impl From<FormatError> for DecodingError {
    fn from(err: FormatError) -> DecodingError {
        DecodingError::Format(err)
    }
}

impl From<FormatErrorInner> for FormatError {
    fn from(inner: FormatErrorInner) -> Self {
        FormatError { inner }
    }
}

impl From<DecodingError> for io::Error {
    fn from(err: DecodingError) -> io::Error {
        match err {
            DecodingError::IoError(err) => err,
            err => io::Error::new(io::ErrorKind::Other, err.to_string()),
        }
    }
}

impl From<TextDecodingError> for DecodingError {
    fn from(tbe: TextDecodingError) -> Self {
        DecodingError::Format(FormatError {
            inner: FormatErrorInner::BadTextEncoding(tbe),
        })
    }
}

/// Decoder configuration options
#[derive(Clone)]
pub struct DecodeOptions {
    ignore_adler32: bool,
    ignore_crc: bool,
    ignore_text_chunk: bool,
    ignore_iccp_chunk: bool,
    skip_ancillary_crc_failures: bool,
}

impl Default for DecodeOptions {
    fn default() -> Self {
        Self {
            ignore_adler32: true,
            ignore_crc: false,
            ignore_text_chunk: false,
            ignore_iccp_chunk: false,
            skip_ancillary_crc_failures: true,
        }
    }
}

impl DecodeOptions {
    /// When set, the decoder will not compute and verify the Adler-32 checksum.
    ///
    /// Defaults to `true`.
    pub fn set_ignore_adler32(&mut self, ignore_adler32: bool) {
        self.ignore_adler32 = ignore_adler32;
    }

    /// When set, the decoder will not compute and verify the CRC code.
    ///
    /// Defaults to `false`.
    pub fn set_ignore_crc(&mut self, ignore_crc: bool) {
        self.ignore_crc = ignore_crc;
    }

    /// Flag to ignore computing and verifying the Adler-32 checksum and CRC
    /// code.
    pub fn set_ignore_checksums(&mut self, ignore_checksums: bool) {
        self.ignore_adler32 = ignore_checksums;
        self.ignore_crc = ignore_checksums;
    }

    /// Ignore text chunks while decoding.
    ///
    /// Defaults to `false`.
    pub fn set_ignore_text_chunk(&mut self, ignore_text_chunk: bool) {
        self.ignore_text_chunk = ignore_text_chunk;
    }

    /// Ignore ICCP chunks while decoding.
    ///
    /// Defaults to `false`.
    pub fn set_ignore_iccp_chunk(&mut self, ignore_iccp_chunk: bool) {
        self.ignore_iccp_chunk = ignore_iccp_chunk;
    }

    /// Ignore ancillary chunks if CRC fails
    ///
    /// Defaults to `true`
    pub fn set_skip_ancillary_crc_failures(&mut self, skip_ancillary_crc_failures: bool) {
        self.skip_ancillary_crc_failures = skip_ancillary_crc_failures;
    }
}

/// PNG StreamingDecoder (low-level interface)
///
/// By default, the decoder does not verify Adler-32 checksum computation. To
/// enable checksum verification, set it with [`StreamingDecoder::set_ignore_adler32`]
/// before starting decompression.
pub struct StreamingDecoder {
    state: Option<State>,
    current_chunk: ChunkState,
    /// The inflater state handling consecutive `IDAT` and `fdAT` chunks.
    inflater: ZlibStream,
    /// The complete image info read from all prior chunks.
    pub(crate) info: Option<Info<'static>>,
    /// The animation chunk sequence number.
    current_seq_no: Option<u32>,
    /// Whether we have already seen a start of an IDAT chunk.  (Used to validate chunk ordering -
    /// some chunk types can only appear before or after an IDAT chunk.)
    have_idat: bool,
    /// Whether we are ready for a start of an `IDAT` chunk sequence.  Initially `true` and set to
    /// `false` when the first sequence of consecutive `IDAT` chunks ends.
    ready_for_idat_chunks: bool,
    /// Whether we are ready for a start of an `fdAT` chunk sequence.  Initially `false`.  Set to
    /// `true` after encountering an `fcTL` chunk. Set to `false` when a sequence of consecutive
    /// `fdAT` chunks ends.
    ready_for_fdat_chunks: bool,
    /// Whether we have already seen an iCCP chunk. Used to prevent parsing of duplicate iCCP chunks.
    have_iccp: bool,
    decode_options: DecodeOptions,
    pub(crate) limits: Limits,
}

struct ChunkState {
    /// The type of the current chunk.
    /// Relevant for `IDAT` and `fdAT` which aggregate consecutive chunks of their own type.
    type_: ChunkType,

    /// Partial crc until now.
    crc: Crc32,

    /// Remaining bytes to be read.
    remaining: u32,

    /// Non-decoded bytes in the chunk.
    raw_bytes: Vec<u8>,
}

impl StreamingDecoder {
    /// Creates a new StreamingDecoder
    ///
    /// Allocates the internal buffers.
    pub fn new() -> StreamingDecoder {
        StreamingDecoder::new_with_options(DecodeOptions::default())
    }

    pub fn new_with_options(decode_options: DecodeOptions) -> StreamingDecoder {
        let mut inflater = ZlibStream::new();
        inflater.set_ignore_adler32(decode_options.ignore_adler32);

        StreamingDecoder {
            state: Some(State::new_u32(U32ValueKind::Signature1stU32)),
            current_chunk: ChunkState::default(),
            inflater,
            info: None,
            current_seq_no: None,
            have_idat: false,
            have_iccp: false,
            ready_for_idat_chunks: true,
            ready_for_fdat_chunks: false,
            decode_options,
            limits: Limits { bytes: usize::MAX },
        }
    }

    /// Resets the StreamingDecoder
    pub fn reset(&mut self) {
        self.state = Some(State::new_u32(U32ValueKind::Signature1stU32));
        self.current_chunk.crc = Crc32::new();
        self.current_chunk.remaining = 0;
        self.current_chunk.raw_bytes.clear();
        self.inflater.reset();
        self.info = None;
        self.current_seq_no = None;
        self.have_idat = false;
    }

    /// Provides access to the inner `info` field
    pub fn info(&self) -> Option<&Info<'static>> {
        self.info.as_ref()
    }

    pub fn set_ignore_text_chunk(&mut self, ignore_text_chunk: bool) {
        self.decode_options.set_ignore_text_chunk(ignore_text_chunk);
    }

    pub fn set_ignore_iccp_chunk(&mut self, ignore_iccp_chunk: bool) {
        self.decode_options.set_ignore_iccp_chunk(ignore_iccp_chunk);
    }

    /// Return whether the decoder is set to ignore the Adler-32 checksum.
    pub fn ignore_adler32(&self) -> bool {
        self.inflater.ignore_adler32()
    }

    /// Set whether to compute and verify the Adler-32 checksum during
    /// decompression. Return `true` if the flag was successfully set.
    ///
    /// The decoder defaults to `true`.
    ///
    /// This flag cannot be modified after decompression has started until the
    /// [`StreamingDecoder`] is reset.
    pub fn set_ignore_adler32(&mut self, ignore_adler32: bool) -> bool {
        self.inflater.set_ignore_adler32(ignore_adler32)
    }

    /// Set whether to compute and verify the Adler-32 checksum during
    /// decompression.
    ///
    /// The decoder defaults to `false`.
    pub fn set_ignore_crc(&mut self, ignore_crc: bool) {
        self.decode_options.set_ignore_crc(ignore_crc)
    }

    /// Ignore ancillary chunks if CRC fails
    ///
    /// Defaults to `true`
    pub fn set_skip_ancillary_crc_failures(&mut self, skip_ancillary_crc_failures: bool) {
        self.decode_options
            .set_skip_ancillary_crc_failures(skip_ancillary_crc_failures)
    }

    /// Low level StreamingDecoder interface.
    ///
    /// Allows to stream partial data to the encoder. Returns a tuple containing the bytes that have
    /// been consumed from the input buffer and the current decoding result. If the decoded chunk
    /// was an image data chunk, it also appends the read data to `image_data`.
    pub fn update(
        &mut self,
        mut buf: &[u8],
        image_data: &mut Vec<u8>,
    ) -> Result<(usize, Decoded), DecodingError> {
        if self.state.is_none() {
            return Err(DecodingError::Parameter(
                ParameterErrorKind::PolledAfterFatalError.into(),
            ));
        }

        let len = buf.len();
        while !buf.is_empty() {
            match self.next_state(buf, image_data) {
                Ok((bytes, Decoded::Nothing)) => buf = &buf[bytes..],
                Ok((bytes, result)) => {
                    buf = &buf[bytes..];
                    return Ok((len - buf.len(), result));
                }
                Err(err) => {
                    debug_assert!(self.state.is_none());
                    return Err(err);
                }
            }
        }
        Ok((len - buf.len(), Decoded::Nothing))
    }

    fn next_state(
        &mut self,
        buf: &[u8],
        image_data: &mut Vec<u8>,
    ) -> Result<(usize, Decoded), DecodingError> {
        use self::State::*;

        // Driver should ensure that state is never None
        let state = self.state.take().unwrap();

        match state {
            U32 {
                kind,
                mut bytes,
                mut accumulated_count,
            } => {
                debug_assert!(accumulated_count <= 4);
                if accumulated_count == 0 && buf.len() >= 4 {
                    // Handling these `accumulated_count` and `buf.len()` values in a separate `if`
                    // branch is not strictly necessary - the `else` statement below is already
                    // capable of handling these values.  The main reason for special-casing these
                    // values is that they occur fairly frequently and special-casing them results
                    // in performance gains.
                    const CONSUMED_BYTES: usize = 4;
                    self.parse_u32(kind, &buf[0..4], image_data)
                        .map(|decoded| (CONSUMED_BYTES, decoded))
                } else {
                    let remaining_count = 4 - accumulated_count;
                    let consumed_bytes = {
                        let available_count = min(remaining_count, buf.len());
                        bytes[accumulated_count..accumulated_count + available_count]
                            .copy_from_slice(&buf[0..available_count]);
                        accumulated_count += available_count;
                        available_count
                    };

                    if accumulated_count < 4 {
                        self.state = Some(U32 {
                            kind,
                            bytes,
                            accumulated_count,
                        });
                        Ok((consumed_bytes, Decoded::Nothing))
                    } else {
                        debug_assert_eq!(accumulated_count, 4);
                        self.parse_u32(kind, &bytes, image_data)
                            .map(|decoded| (consumed_bytes, decoded))
                    }
                }
            }
            ParseChunkData(type_str) => {
                debug_assert!(type_str != IDAT && type_str != chunk::fdAT);
                if self.current_chunk.remaining == 0 {
                    // Got complete chunk.
                    Ok((0, self.parse_chunk(type_str)?))
                } else {
                    // Make sure we have room to read more of the chunk.
                    // We need it fully before parsing.
                    self.reserve_current_chunk()?;

                    self.state = Some(ReadChunkData(type_str));
                    Ok((0, Decoded::PartialChunk(type_str)))
                }
            }
            ReadChunkData(type_str) => {
                debug_assert!(type_str != IDAT && type_str != chunk::fdAT);
                if self.current_chunk.remaining == 0 {
                    self.state = Some(State::new_u32(U32ValueKind::Crc(type_str)));
                    Ok((0, Decoded::Nothing))
                } else {
                    let ChunkState {
                        crc,
                        remaining,
                        raw_bytes,
                        type_: _,
                    } = &mut self.current_chunk;

                    let buf_avail = raw_bytes.capacity() - raw_bytes.len();
                    let bytes_avail = min(buf.len(), buf_avail);
                    let n = min(*remaining, bytes_avail as u32);
                    if buf_avail == 0 {
                        self.state = Some(ParseChunkData(type_str));
                        Ok((0, Decoded::Nothing))
                    } else {
                        let buf = &buf[..n as usize];
                        if !self.decode_options.ignore_crc {
                            crc.update(buf);
                        }
                        raw_bytes.extend_from_slice(buf);

                        *remaining -= n;
                        if *remaining == 0 {
                            self.state = Some(ParseChunkData(type_str));
                        } else {
                            self.state = Some(ReadChunkData(type_str));
                        }
                        Ok((n as usize, Decoded::Nothing))
                    }
                }
            }
            ImageData(type_str) => {
                debug_assert!(type_str == IDAT || type_str == chunk::fdAT);
                let len = std::cmp::min(buf.len(), self.current_chunk.remaining as usize);
                let buf = &buf[..len];
                let consumed = self.inflater.decompress(buf, image_data)?;
                self.current_chunk.crc.update(&buf[..consumed]);
                self.current_chunk.remaining -= consumed as u32;
                if self.current_chunk.remaining == 0 {
                    self.state = Some(State::new_u32(U32ValueKind::Crc(type_str)));
                } else {
                    self.state = Some(ImageData(type_str));
                }
                Ok((consumed, Decoded::ImageData))
            }
        }
    }

    fn parse_u32(
        &mut self,
        kind: U32ValueKind,
        u32_be_bytes: &[u8],
        image_data: &mut Vec<u8>,
    ) -> Result<Decoded, DecodingError> {
        debug_assert_eq!(u32_be_bytes.len(), 4);
        let bytes = u32_be_bytes.try_into().unwrap();
        let val = u32::from_be_bytes(bytes);

        match kind {
            U32ValueKind::Signature1stU32 => {
                if bytes == [137, 80, 78, 71] {
                    self.state = Some(State::new_u32(U32ValueKind::Signature2ndU32));
                    Ok(Decoded::Nothing)
                } else {
                    Err(DecodingError::Format(
                        FormatErrorInner::InvalidSignature.into(),
                    ))
                }
            }
            U32ValueKind::Signature2ndU32 => {
                if bytes == [13, 10, 26, 10] {
                    self.state = Some(State::new_u32(U32ValueKind::Length));
                    Ok(Decoded::Nothing)
                } else {
                    Err(DecodingError::Format(
                        FormatErrorInner::InvalidSignature.into(),
                    ))
                }
            }
            U32ValueKind::Length => {
                self.state = Some(State::new_u32(U32ValueKind::Type { length: val }));
                Ok(Decoded::Nothing)
            }
            U32ValueKind::Type { length } => {
                let type_str = ChunkType(bytes);
                if self.info.is_none() && type_str != IHDR {
                    return Err(DecodingError::Format(
                        FormatErrorInner::ChunkBeforeIhdr { kind: type_str }.into(),
                    ));
                }
                if type_str != self.current_chunk.type_
                    && (self.current_chunk.type_ == IDAT || self.current_chunk.type_ == chunk::fdAT)
                {
                    self.current_chunk.type_ = type_str;
                    self.inflater.finish_compressed_chunks(image_data)?;
                    self.inflater.reset();
                    self.ready_for_idat_chunks = false;
                    self.ready_for_fdat_chunks = false;
                    self.state = Some(State::U32 {
                        kind,
                        bytes,
                        accumulated_count: 4,
                    });
                    return Ok(Decoded::ImageDataFlushed);
                }
                self.state = match type_str {
                    chunk::fdAT => {
                        if !self.ready_for_fdat_chunks {
                            return Err(DecodingError::Format(
                                FormatErrorInner::UnexpectedRestartOfDataChunkSequence {
                                    kind: chunk::fdAT,
                                }
                                .into(),
                            ));
                        }
                        if length < 4 {
                            return Err(DecodingError::Format(
                                FormatErrorInner::FdatShorterThanFourBytes.into(),
                            ));
                        }
                        Some(State::new_u32(U32ValueKind::ApngSequenceNumber))
                    }
                    IDAT => {
                        if !self.ready_for_idat_chunks {
                            return Err(DecodingError::Format(
                                FormatErrorInner::UnexpectedRestartOfDataChunkSequence {
                                    kind: IDAT,
                                }
                                .into(),
                            ));
                        }
                        self.have_idat = true;
                        Some(State::ImageData(type_str))
                    }
                    _ => Some(State::ReadChunkData(type_str)),
                };
                self.current_chunk.type_ = type_str;
                if !self.decode_options.ignore_crc {
                    self.current_chunk.crc.reset();
                    self.current_chunk.crc.update(&type_str.0);
                }
                self.current_chunk.remaining = length;
                self.current_chunk.raw_bytes.clear();
                Ok(Decoded::ChunkBegin(length, type_str))
            }
            U32ValueKind::Crc(type_str) => {
                // If ignore_crc is set, do not calculate CRC. We set
                // sum=val so that it short-circuits to true in the next
                // if-statement block
                let sum = if self.decode_options.ignore_crc {
                    val
                } else {
                    self.current_chunk.crc.clone().finalize()
                };

                if val == sum || CHECKSUM_DISABLED {
                    if type_str == IEND {
                        debug_assert!(self.state.is_none());
                        Ok(Decoded::ImageEnd)
                    } else {
                        self.state = Some(State::new_u32(U32ValueKind::Length));
                        Ok(Decoded::ChunkComplete(val, type_str))
                    }
                } else if self.decode_options.skip_ancillary_crc_failures
                    && !chunk::is_critical(type_str)
                {
                    // Ignore ancillary chunk with invalid CRC
                    self.state = Some(State::new_u32(U32ValueKind::Length));
                    Ok(Decoded::Nothing)
                } else {
                    Err(DecodingError::Format(
                        FormatErrorInner::CrcMismatch {
                            crc_val: val,
                            crc_sum: sum,
                            chunk: type_str,
                        }
                        .into(),
                    ))
                }
            }
            U32ValueKind::ApngSequenceNumber => {
                debug_assert_eq!(self.current_chunk.type_, chunk::fdAT);
                let next_seq_no = val;

                // Should be verified by the FdatShorterThanFourBytes check earlier.
                debug_assert!(self.current_chunk.remaining >= 4);
                self.current_chunk.remaining -= 4;

                if let Some(seq_no) = self.current_seq_no {
                    if next_seq_no != seq_no + 1 {
                        return Err(DecodingError::Format(
                            FormatErrorInner::ApngOrder {
                                present: next_seq_no,
                                expected: seq_no + 1,
                            }
                            .into(),
                        ));
                    }
                    self.current_seq_no = Some(next_seq_no);
                } else {
                    return Err(DecodingError::Format(FormatErrorInner::MissingFctl.into()));
                }

                if !self.decode_options.ignore_crc {
                    let data = next_seq_no.to_be_bytes();
                    self.current_chunk.crc.update(&data);
                }

                self.state = Some(State::ImageData(chunk::fdAT));
                Ok(Decoded::PartialChunk(chunk::fdAT))
            }
        }
    }

    fn reserve_current_chunk(&mut self) -> Result<(), DecodingError> {
        let max = self.limits.bytes;
        let buffer = &mut self.current_chunk.raw_bytes;

        // Double if necessary, but no more than until the limit is reached.
        let reserve_size = max.saturating_sub(buffer.capacity()).min(buffer.len());
        self.limits.reserve_bytes(reserve_size)?;
        buffer.reserve_exact(reserve_size);

        if buffer.capacity() == buffer.len() {
            Err(DecodingError::LimitsExceeded)
        } else {
            Ok(())
        }
    }

    fn parse_chunk(&mut self, type_str: ChunkType) -> Result<Decoded, DecodingError> {
        self.state = Some(State::new_u32(U32ValueKind::Crc(type_str)));
        let parse_result = match type_str {
            IHDR => self.parse_ihdr(),
            chunk::sBIT => self.parse_sbit(),
            chunk::PLTE => self.parse_plte(),
            chunk::tRNS => self.parse_trns(),
            chunk::pHYs => self.parse_phys(),
            chunk::gAMA => self.parse_gama(),
            chunk::acTL => self.parse_actl(),
            chunk::fcTL => self.parse_fctl(),
            chunk::cHRM => self.parse_chrm(),
            chunk::sRGB => self.parse_srgb(),
            chunk::cICP => Ok(self.parse_cicp()),
            chunk::mDCV => Ok(self.parse_mdcv()),
            chunk::cLLI => Ok(self.parse_clli()),
            chunk::bKGD => Ok(self.parse_bkgd()),
            chunk::iCCP if !self.decode_options.ignore_iccp_chunk => self.parse_iccp(),
            chunk::tEXt if !self.decode_options.ignore_text_chunk => self.parse_text(),
            chunk::zTXt if !self.decode_options.ignore_text_chunk => self.parse_ztxt(),
            chunk::iTXt if !self.decode_options.ignore_text_chunk => self.parse_itxt(),
            _ => Ok(Decoded::PartialChunk(type_str)),
        };

        parse_result.map_err(|e| {
            self.state = None;
            match e {
                // `parse_chunk` is invoked after gathering **all** bytes of a chunk, so
                // `UnexpectedEof` from something like `read_be` is permanent and indicates an
                // invalid PNG that should be represented as a `FormatError`, rather than as a
                // (potentially recoverable) `IoError` / `UnexpectedEof`.
                DecodingError::IoError(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    let fmt_err: FormatError =
                        FormatErrorInner::ChunkTooShort { kind: type_str }.into();
                    fmt_err.into()
                }
                e => e,
            }
        })
    }

    fn parse_fctl(&mut self) -> Result<Decoded, DecodingError> {
        let mut buf = &self.current_chunk.raw_bytes[..];
        let next_seq_no = buf.read_be()?;

        // Assuming that fcTL is required before *every* fdAT-sequence
        self.current_seq_no = Some(if let Some(seq_no) = self.current_seq_no {
            if next_seq_no != seq_no + 1 {
                return Err(DecodingError::Format(
                    FormatErrorInner::ApngOrder {
                        expected: seq_no + 1,
                        present: next_seq_no,
                    }
                    .into(),
                ));
            }
            next_seq_no
        } else {
            if next_seq_no != 0 {
                return Err(DecodingError::Format(
                    FormatErrorInner::ApngOrder {
                        expected: 0,
                        present: next_seq_no,
                    }
                    .into(),
                ));
            }
            0
        });
        self.inflater.reset();
        self.ready_for_fdat_chunks = true;
        let fc = FrameControl {
            sequence_number: next_seq_no,
            width: buf.read_be()?,
            height: buf.read_be()?,
            x_offset: buf.read_be()?,
            y_offset: buf.read_be()?,
            delay_num: buf.read_be()?,
            delay_den: buf.read_be()?,
            dispose_op: {
                let dispose_op = buf.read_be()?;
                match DisposeOp::from_u8(dispose_op) {
                    Some(dispose_op) => dispose_op,
                    None => {
                        return Err(DecodingError::Format(
                            FormatErrorInner::InvalidDisposeOp(dispose_op).into(),
                        ))
                    }
                }
            },
            blend_op: {
                let blend_op = buf.read_be()?;
                match BlendOp::from_u8(blend_op) {
                    Some(blend_op) => blend_op,
                    None => {
                        return Err(DecodingError::Format(
                            FormatErrorInner::InvalidBlendOp(blend_op).into(),
                        ))
                    }
                }
            },
        };
        self.info.as_ref().unwrap().validate(&fc)?;
        self.info.as_mut().unwrap().frame_control = Some(fc);
        Ok(Decoded::FrameControl(fc))
    }

    fn parse_actl(&mut self) -> Result<Decoded, DecodingError> {
        if self.have_idat {
            Err(DecodingError::Format(
                FormatErrorInner::AfterIdat { kind: chunk::acTL }.into(),
            ))
        } else {
            let mut buf = &self.current_chunk.raw_bytes[..];
            let actl = AnimationControl {
                num_frames: buf.read_be()?,
                num_plays: buf.read_be()?,
            };
            self.info.as_mut().unwrap().animation_control = Some(actl);
            Ok(Decoded::AnimationControl(actl))
        }
    }

    fn parse_plte(&mut self) -> Result<Decoded, DecodingError> {
        let info = self.info.as_mut().unwrap();
        if info.palette.is_some() {
            // Only one palette is allowed
            Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: chunk::PLTE }.into(),
            ))
        } else {
            self.limits
                .reserve_bytes(self.current_chunk.raw_bytes.len())?;
            info.palette = Some(Cow::Owned(self.current_chunk.raw_bytes.clone()));
            Ok(Decoded::Nothing)
        }
    }

    fn parse_sbit(&mut self) -> Result<Decoded, DecodingError> {
        let mut parse = || {
            let info = self.info.as_mut().unwrap();
            if info.palette.is_some() {
                return Err(DecodingError::Format(
                    FormatErrorInner::AfterPlte { kind: chunk::sBIT }.into(),
                ));
            }

            if self.have_idat {
                return Err(DecodingError::Format(
                    FormatErrorInner::AfterIdat { kind: chunk::sBIT }.into(),
                ));
            }

            if info.sbit.is_some() {
                return Err(DecodingError::Format(
                    FormatErrorInner::DuplicateChunk { kind: chunk::sBIT }.into(),
                ));
            }

            let (color_type, bit_depth) = { (info.color_type, info.bit_depth) };
            // The sample depth for color type 3 is fixed at eight bits.
            let sample_depth = if color_type == ColorType::Indexed {
                BitDepth::Eight
            } else {
                bit_depth
            };
            self.limits
                .reserve_bytes(self.current_chunk.raw_bytes.len())?;
            let vec = self.current_chunk.raw_bytes.clone();
            let len = vec.len();

            // expected lenth of the chunk
            let expected = match color_type {
                ColorType::Grayscale => 1,
                ColorType::Rgb | ColorType::Indexed => 3,
                ColorType::GrayscaleAlpha => 2,
                ColorType::Rgba => 4,
            };

            // Check if the sbit chunk size is valid.
            if expected != len {
                return Err(DecodingError::Format(
                    FormatErrorInner::InvalidSbitChunkSize {
                        color_type,
                        expected,
                        len,
                    }
                    .into(),
                ));
            }

            for sbit in &vec {
                if *sbit < 1 || *sbit > sample_depth as u8 {
                    return Err(DecodingError::Format(
                        FormatErrorInner::InvalidSbit {
                            sample_depth,
                            sbit: *sbit,
                        }
                        .into(),
                    ));
                }
            }
            info.sbit = Some(Cow::Owned(vec));
            Ok(Decoded::Nothing)
        };

        parse().ok();
        Ok(Decoded::Nothing)
    }

    fn parse_trns(&mut self) -> Result<Decoded, DecodingError> {
        let info = self.info.as_mut().unwrap();
        if info.trns.is_some() {
            return Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: chunk::PLTE }.into(),
            ));
        }
        let (color_type, bit_depth) = { (info.color_type, info.bit_depth as u8) };
        self.limits
            .reserve_bytes(self.current_chunk.raw_bytes.len())?;
        let mut vec = self.current_chunk.raw_bytes.clone();
        let len = vec.len();
        match color_type {
            ColorType::Grayscale => {
                if len < 2 {
                    return Err(DecodingError::Format(
                        FormatErrorInner::ShortPalette { expected: 2, len }.into(),
                    ));
                }
                if bit_depth < 16 {
                    vec[0] = vec[1];
                    vec.truncate(1);
                }
                info.trns = Some(Cow::Owned(vec));
                Ok(Decoded::Nothing)
            }
            ColorType::Rgb => {
                if len < 6 {
                    return Err(DecodingError::Format(
                        FormatErrorInner::ShortPalette { expected: 6, len }.into(),
                    ));
                }
                if bit_depth < 16 {
                    vec[0] = vec[1];
                    vec[1] = vec[3];
                    vec[2] = vec[5];
                    vec.truncate(3);
                }
                info.trns = Some(Cow::Owned(vec));
                Ok(Decoded::Nothing)
            }
            ColorType::Indexed => {
                // The transparency chunk must be after the palette chunk and
                // before the data chunk.
                if info.palette.is_none() {
                    return Err(DecodingError::Format(
                        FormatErrorInner::BeforePlte { kind: chunk::tRNS }.into(),
                    ));
                } else if self.have_idat {
                    return Err(DecodingError::Format(
                        FormatErrorInner::OutsidePlteIdat { kind: chunk::tRNS }.into(),
                    ));
                }

                info.trns = Some(Cow::Owned(vec));
                Ok(Decoded::Nothing)
            }
            c => Err(DecodingError::Format(
                FormatErrorInner::ColorWithBadTrns(c).into(),
            )),
        }
    }

    fn parse_phys(&mut self) -> Result<Decoded, DecodingError> {
        let info = self.info.as_mut().unwrap();
        if self.have_idat {
            Err(DecodingError::Format(
                FormatErrorInner::AfterIdat { kind: chunk::pHYs }.into(),
            ))
        } else if info.pixel_dims.is_some() {
            Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: chunk::pHYs }.into(),
            ))
        } else {
            let mut buf = &self.current_chunk.raw_bytes[..];
            let xppu = buf.read_be()?;
            let yppu = buf.read_be()?;
            let unit = buf.read_be()?;
            let unit = match Unit::from_u8(unit) {
                Some(unit) => unit,
                None => {
                    return Err(DecodingError::Format(
                        FormatErrorInner::InvalidUnit(unit).into(),
                    ))
                }
            };
            let pixel_dims = PixelDimensions { xppu, yppu, unit };
            info.pixel_dims = Some(pixel_dims);
            Ok(Decoded::PixelDimensions(pixel_dims))
        }
    }

    fn parse_chrm(&mut self) -> Result<Decoded, DecodingError> {
        let info = self.info.as_mut().unwrap();
        if self.have_idat {
            Err(DecodingError::Format(
                FormatErrorInner::AfterIdat { kind: chunk::cHRM }.into(),
            ))
        } else if info.chrm_chunk.is_some() {
            Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: chunk::cHRM }.into(),
            ))
        } else {
            let mut buf = &self.current_chunk.raw_bytes[..];
            let white_x: u32 = buf.read_be()?;
            let white_y: u32 = buf.read_be()?;
            let red_x: u32 = buf.read_be()?;
            let red_y: u32 = buf.read_be()?;
            let green_x: u32 = buf.read_be()?;
            let green_y: u32 = buf.read_be()?;
            let blue_x: u32 = buf.read_be()?;
            let blue_y: u32 = buf.read_be()?;

            let source_chromaticities = SourceChromaticities {
                white: (
                    ScaledFloat::from_scaled(white_x),
                    ScaledFloat::from_scaled(white_y),
                ),
                red: (
                    ScaledFloat::from_scaled(red_x),
                    ScaledFloat::from_scaled(red_y),
                ),
                green: (
                    ScaledFloat::from_scaled(green_x),
                    ScaledFloat::from_scaled(green_y),
                ),
                blue: (
                    ScaledFloat::from_scaled(blue_x),
                    ScaledFloat::from_scaled(blue_y),
                ),
            };

            info.chrm_chunk = Some(source_chromaticities);
            // Ignore chromaticities if sRGB profile is used.
            if info.srgb.is_none() {
                info.source_chromaticities = Some(source_chromaticities);
            }

            Ok(Decoded::Nothing)
        }
    }

    fn parse_gama(&mut self) -> Result<Decoded, DecodingError> {
        let info = self.info.as_mut().unwrap();
        if self.have_idat {
            Err(DecodingError::Format(
                FormatErrorInner::AfterIdat { kind: chunk::gAMA }.into(),
            ))
        } else if info.gama_chunk.is_some() {
            Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: chunk::gAMA }.into(),
            ))
        } else {
            let mut buf = &self.current_chunk.raw_bytes[..];
            let source_gamma: u32 = buf.read_be()?;
            let source_gamma = ScaledFloat::from_scaled(source_gamma);

            info.gama_chunk = Some(source_gamma);
            // Ignore chromaticities if sRGB profile is used.
            if info.srgb.is_none() {
                info.source_gamma = Some(source_gamma);
            }

            Ok(Decoded::Nothing)
        }
    }

    fn parse_srgb(&mut self) -> Result<Decoded, DecodingError> {
        let info = self.info.as_mut().unwrap();
        if self.have_idat {
            Err(DecodingError::Format(
                FormatErrorInner::AfterIdat { kind: chunk::acTL }.into(),
            ))
        } else if info.srgb.is_some() {
            Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: chunk::sRGB }.into(),
            ))
        } else {
            let mut buf = &self.current_chunk.raw_bytes[..];
            let raw: u8 = buf.read_be()?; // BE is is nonsense for single bytes, but this way the size is checked.
            let rendering_intent = crate::SrgbRenderingIntent::from_raw(raw).ok_or_else(|| {
                FormatError::from(FormatErrorInner::InvalidSrgbRenderingIntent(raw))
            })?;

            // Set srgb and override source gamma and chromaticities.
            info.srgb = Some(rendering_intent);
            info.source_gamma = Some(crate::srgb::substitute_gamma());
            info.source_chromaticities = Some(crate::srgb::substitute_chromaticities());
            Ok(Decoded::Nothing)
        }
    }

    // NOTE: This function cannot return `DecodingError` and handles parsing
    // errors or spec violations as-if the chunk was missing.  See
    // https://github.com/image-rs/image-png/issues/525 for more discussion.
    fn parse_cicp(&mut self) -> Decoded {
        fn parse(mut buf: &[u8]) -> Result<CodingIndependentCodePoints, std::io::Error> {
            let color_primaries: u8 = buf.read_be()?;
            let transfer_function: u8 = buf.read_be()?;
            let matrix_coefficients: u8 = buf.read_be()?;
            let is_video_full_range_image = {
                let flag: u8 = buf.read_be()?;
                match flag {
                    0 => false,
                    1 => true,
                    _ => {
                        return Err(std::io::ErrorKind::InvalidData.into());
                    }
                }
            };

            // RGB is currently the only supported color model in PNG, and as
            // such Matrix Coefficients shall be set to 0.
            if matrix_coefficients != 0 {
                return Err(std::io::ErrorKind::InvalidData.into());
            }

            if !buf.is_empty() {
                return Err(std::io::ErrorKind::InvalidData.into());
            }

            Ok(CodingIndependentCodePoints {
                color_primaries,
                transfer_function,
                matrix_coefficients,
                is_video_full_range_image,
            })
        }

        // The spec requires that the cICP chunk MUST come before the PLTE and IDAT chunks.
        // Additionally, we ignore a second, duplicated cICP chunk (if any).
        let info = self.info.as_mut().unwrap();
        let is_before_plte_and_idat = !self.have_idat && info.palette.is_none();
        if is_before_plte_and_idat && info.coding_independent_code_points.is_none() {
            info.coding_independent_code_points = parse(&self.current_chunk.raw_bytes[..]).ok();
        }

        Decoded::Nothing
    }

    // NOTE: This function cannot return `DecodingError` and handles parsing
    // errors or spec violations as-if the chunk was missing.  See
    // https://github.com/image-rs/image-png/issues/525 for more discussion.
    fn parse_mdcv(&mut self) -> Decoded {
        fn parse(mut buf: &[u8]) -> Result<MasteringDisplayColorVolume, std::io::Error> {
            let red_x: u16 = buf.read_be()?;
            let red_y: u16 = buf.read_be()?;
            let green_x: u16 = buf.read_be()?;
            let green_y: u16 = buf.read_be()?;
            let blue_x: u16 = buf.read_be()?;
            let blue_y: u16 = buf.read_be()?;
            let white_x: u16 = buf.read_be()?;
            let white_y: u16 = buf.read_be()?;
            fn scale(chunk: u16) -> ScaledFloat {
                // `ScaledFloat::SCALING` is hardcoded to 100_000, which works
                // well for the `cHRM` chunk where the spec says that "a value
                // of 0.3127 would be stored as the integer 31270".  In the
                // `mDCV` chunk the spec says that "0.708, 0.292)" is stored as
                // "{ 35400, 14600 }", using a scaling factor of 50_000, so we
                // multiply by 2 before converting.
                ScaledFloat::from_scaled((chunk as u32) * 2)
            }
            let chromaticities = SourceChromaticities {
                white: (scale(white_x), scale(white_y)),
                red: (scale(red_x), scale(red_y)),
                green: (scale(green_x), scale(green_y)),
                blue: (scale(blue_x), scale(blue_y)),
            };
            let max_luminance: u32 = buf.read_be()?;
            let min_luminance: u32 = buf.read_be()?;
            if !buf.is_empty() {
                return Err(std::io::ErrorKind::InvalidData.into());
            }
            Ok(MasteringDisplayColorVolume {
                chromaticities,
                max_luminance,
                min_luminance,
            })
        }

        // The spec requires that the mDCV chunk MUST come before the PLTE and IDAT chunks.
        // Additionally, we ignore a second, duplicated mDCV chunk (if any).
        let info = self.info.as_mut().unwrap();
        let is_before_plte_and_idat = !self.have_idat && info.palette.is_none();
        if is_before_plte_and_idat && info.mastering_display_color_volume.is_none() {
            info.mastering_display_color_volume = parse(&self.current_chunk.raw_bytes[..]).ok();
        }

        Decoded::Nothing
    }

    // NOTE: This function cannot return `DecodingError` and handles parsing
    // errors or spec violations as-if the chunk was missing.  See
    // https://github.com/image-rs/image-png/issues/525 for more discussion.
    fn parse_clli(&mut self) -> Decoded {
        fn parse(mut buf: &[u8]) -> Result<ContentLightLevelInfo, std::io::Error> {
            let max_content_light_level: u32 = buf.read_be()?;
            let max_frame_average_light_level: u32 = buf.read_be()?;
            if !buf.is_empty() {
                return Err(std::io::ErrorKind::InvalidData.into());
            }
            Ok(ContentLightLevelInfo {
                max_content_light_level,
                max_frame_average_light_level,
            })
        }

        // We ignore a second, duplicated cLLI chunk (if any).
        let info = self.info.as_mut().unwrap();
        if info.content_light_level.is_none() {
            info.content_light_level = parse(&self.current_chunk.raw_bytes[..]).ok();
        }

        Decoded::Nothing
    }

    fn parse_iccp(&mut self) -> Result<Decoded, DecodingError> {
        if self.have_idat {
            Err(DecodingError::Format(
                FormatErrorInner::AfterIdat { kind: chunk::iCCP }.into(),
            ))
        } else if self.have_iccp {
            // We have already encountered an iCCP chunk before.
            //
            // Section "4.2.2.4. iCCP Embedded ICC profile" of the spec says:
            //   > A file should contain at most one embedded profile,
            //   > whether explicit like iCCP or implicit like sRGB.
            // but
            //   * This is a "should", not a "must"
            //   * The spec also says that "All ancillary chunks are optional, in the sense that
            //     [...] decoders can ignore them."
            //   * The reference implementation (libpng) ignores the subsequent iCCP chunks
            //     (treating them as a benign error).
            Ok(Decoded::Nothing)
        } else {
            self.have_iccp = true;
            let _ = self.parse_iccp_raw();
            Ok(Decoded::Nothing)
        }
    }

    fn parse_iccp_raw(&mut self) -> Result<(), DecodingError> {
        let info = self.info.as_mut().unwrap();
        let mut buf = &self.current_chunk.raw_bytes[..];

        // read profile name
        for len in 0..=80 {
            let raw: u8 = buf.read_be()?;
            if (raw == 0 && len == 0) || (raw != 0 && len == 80) {
                return Err(DecodingError::from(TextDecodingError::InvalidKeywordSize));
            }
            if raw == 0 {
                break;
            }
        }

        match buf.read_be()? {
            // compression method
            0u8 => (),
            n => {
                return Err(DecodingError::Format(
                    FormatErrorInner::UnknownCompressionMethod(n).into(),
                ))
            }
        }

        match fdeflate::decompress_to_vec_bounded(buf, self.limits.bytes) {
            Ok(profile) => {
                self.limits.reserve_bytes(profile.len())?;
                info.icc_profile = Some(Cow::Owned(profile));
            }
            Err(fdeflate::BoundedDecompressionError::DecompressionError { inner: err }) => {
                return Err(DecodingError::Format(
                    FormatErrorInner::CorruptFlateStream { err }.into(),
                ))
            }
            Err(fdeflate::BoundedDecompressionError::OutputTooLarge { .. }) => {
                return Err(DecodingError::LimitsExceeded);
            }
        }

        Ok(())
    }

    fn parse_ihdr(&mut self) -> Result<Decoded, DecodingError> {
        if self.info.is_some() {
            return Err(DecodingError::Format(
                FormatErrorInner::DuplicateChunk { kind: IHDR }.into(),
            ));
        }
        let mut buf = &self.current_chunk.raw_bytes[..];
        let width = buf.read_be()?;
        let height = buf.read_be()?;
        if width == 0 || height == 0 {
            return Err(DecodingError::Format(
                FormatErrorInner::InvalidDimensions.into(),
            ));
        }
        let bit_depth = buf.read_be()?;
        let bit_depth = match BitDepth::from_u8(bit_depth) {
            Some(bits) => bits,
            None => {
                return Err(DecodingError::Format(
                    FormatErrorInner::InvalidBitDepth(bit_depth).into(),
                ))
            }
        };
        let color_type = buf.read_be()?;
        let color_type = match ColorType::from_u8(color_type) {
            Some(color_type) => {
                if color_type.is_combination_invalid(bit_depth) {
                    return Err(DecodingError::Format(
                        FormatErrorInner::InvalidColorBitDepth {
                            color_type,
                            bit_depth,
                        }
                        .into(),
                    ));
                } else {
                    color_type
                }
            }
            None => {
                return Err(DecodingError::Format(
                    FormatErrorInner::InvalidColorType(color_type).into(),
                ))
            }
        };
        match buf.read_be()? {
            // compression method
            0u8 => (),
            n => {
                return Err(DecodingError::Format(
                    FormatErrorInner::UnknownCompressionMethod(n).into(),
                ))
            }
        }
        match buf.read_be()? {
            // filter method
            0u8 => (),
            n => {
                return Err(DecodingError::Format(
                    FormatErrorInner::UnknownFilterMethod(n).into(),
                ))
            }
        }
        let interlaced = match buf.read_be()? {
            0u8 => false,
            1 => true,
            n => {
                return Err(DecodingError::Format(
                    FormatErrorInner::UnknownInterlaceMethod(n).into(),
                ))
            }
        };

        if let Some(mut raw_row_len) = color_type.checked_raw_row_length(bit_depth, width) {
            if interlaced {
                // This overshoots, but overestimating should be fine.
                // TODO: Calculate **exact** IDAT size for interlaced images.
                raw_row_len = raw_row_len.saturating_mul(2);
            }
            self.inflater
                .set_max_total_output((height as usize).saturating_mul(raw_row_len));
        }

        self.info = Some(Info {
            width,
            height,
            bit_depth,
            color_type,
            interlaced,
            ..Default::default()
        });

        Ok(Decoded::Header(
            width, height, bit_depth, color_type, interlaced,
        ))
    }

    fn split_keyword(buf: &[u8]) -> Result<(&[u8], &[u8]), DecodingError> {
        let null_byte_index = buf
            .iter()
            .position(|&b| b == 0)
            .ok_or_else(|| DecodingError::from(TextDecodingError::MissingNullSeparator))?;

        if null_byte_index == 0 || null_byte_index > 79 {
            return Err(DecodingError::from(TextDecodingError::InvalidKeywordSize));
        }

        Ok((&buf[..null_byte_index], &buf[null_byte_index + 1..]))
    }

    fn parse_text(&mut self) -> Result<Decoded, DecodingError> {
        let buf = &self.current_chunk.raw_bytes[..];
        self.limits.reserve_bytes(buf.len())?;

        let (keyword_slice, value_slice) = Self::split_keyword(buf)?;

        self.info
            .as_mut()
            .unwrap()
            .uncompressed_latin1_text
            .push(TEXtChunk::decode(keyword_slice, value_slice).map_err(DecodingError::from)?);

        Ok(Decoded::Nothing)
    }

    fn parse_ztxt(&mut self) -> Result<Decoded, DecodingError> {
        let buf = &self.current_chunk.raw_bytes[..];
        self.limits.reserve_bytes(buf.len())?;

        let (keyword_slice, value_slice) = Self::split_keyword(buf)?;

        let compression_method = *value_slice
            .first()
            .ok_or_else(|| DecodingError::from(TextDecodingError::InvalidCompressionMethod))?;

        let text_slice = &value_slice[1..];

        self.info.as_mut().unwrap().compressed_latin1_text.push(
            ZTXtChunk::decode(keyword_slice, compression_method, text_slice)
                .map_err(DecodingError::from)?,
        );

        Ok(Decoded::Nothing)
    }

    fn parse_itxt(&mut self) -> Result<Decoded, DecodingError> {
        let buf = &self.current_chunk.raw_bytes[..];
        self.limits.reserve_bytes(buf.len())?;

        let (keyword_slice, value_slice) = Self::split_keyword(buf)?;

        let compression_flag = *value_slice
            .first()
            .ok_or_else(|| DecodingError::from(TextDecodingError::MissingCompressionFlag))?;

        let compression_method = *value_slice
            .get(1)
            .ok_or_else(|| DecodingError::from(TextDecodingError::InvalidCompressionMethod))?;

        let second_null_byte_index = value_slice[2..]
            .iter()
            .position(|&b| b == 0)
            .ok_or_else(|| DecodingError::from(TextDecodingError::MissingNullSeparator))?
            + 2;

        let language_tag_slice = &value_slice[2..second_null_byte_index];

        let third_null_byte_index = value_slice[second_null_byte_index + 1..]
            .iter()
            .position(|&b| b == 0)
            .ok_or_else(|| DecodingError::from(TextDecodingError::MissingNullSeparator))?
            + (second_null_byte_index + 1);

        let translated_keyword_slice =
            &value_slice[second_null_byte_index + 1..third_null_byte_index];

        let text_slice = &value_slice[third_null_byte_index + 1..];

        self.info.as_mut().unwrap().utf8_text.push(
            ITXtChunk::decode(
                keyword_slice,
                compression_flag,
                compression_method,
                language_tag_slice,
                translated_keyword_slice,
                text_slice,
            )
            .map_err(DecodingError::from)?,
        );

        Ok(Decoded::Nothing)
    }

    // NOTE: This function cannot return `DecodingError` and handles parsing
    // errors or spec violations as-if the chunk was missing.  See
    // https://github.com/image-rs/image-png/issues/525 for more discussion.
    fn parse_bkgd(&mut self) -> Decoded {
        let info = self.info.as_mut().unwrap();
        if info.bkgd.is_none() && !self.have_idat {
            let expected = match info.color_type {
                ColorType::Indexed => {
                    if info.palette.is_none() {
                        return Decoded::Nothing;
                    };
                    1
                }
                ColorType::Grayscale | ColorType::GrayscaleAlpha => 2,
                ColorType::Rgb | ColorType::Rgba => 6,
            };
            let vec = self.current_chunk.raw_bytes.clone();
            let len = vec.len();
            if len == expected {
                info.bkgd = Some(Cow::Owned(vec));
            }
        }

        Decoded::Nothing
    }
}

impl Info<'_> {
    fn validate(&self, fc: &FrameControl) -> Result<(), DecodingError> {
        if fc.width == 0 || fc.height == 0 {
            return Err(DecodingError::Format(
                FormatErrorInner::InvalidDimensions.into(),
            ));
        }

        // Validate mathematically: fc.width + fc.x_offset <= self.width
        let in_x_bounds = Some(fc.width) <= self.width.checked_sub(fc.x_offset);
        // Validate mathematically: fc.height + fc.y_offset <= self.height
        let in_y_bounds = Some(fc.height) <= self.height.checked_sub(fc.y_offset);

        if !in_x_bounds || !in_y_bounds {
            return Err(DecodingError::Format(
                // TODO: do we want to display the bad bounds?
                FormatErrorInner::BadSubFrameBounds {}.into(),
            ));
        }

        Ok(())
    }
}

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

impl Default for ChunkState {
    fn default() -> Self {
        ChunkState {
            type_: ChunkType([0; 4]),
            crc: Crc32::new(),
            remaining: 0,
            raw_bytes: Vec::with_capacity(CHUNK_BUFFER_SIZE),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::ScaledFloat;
    use super::SourceChromaticities;
    use crate::test_utils::*;
    use crate::{Decoder, DecodingError, Reader};
    use approx::assert_relative_eq;
    use byteorder::WriteBytesExt;
    use std::borrow::Cow;
    use std::cell::RefCell;
    use std::collections::VecDeque;
    use std::fs::File;
    use std::io::{ErrorKind, Read, Write};
    use std::rc::Rc;

    #[test]
    fn image_gamma() -> Result<(), ()> {
        fn trial(path: &str, expected: Option<ScaledFloat>) {
            let decoder = crate::Decoder::new(File::open(path).unwrap());
            let reader = decoder.read_info().unwrap();
            let actual: Option<ScaledFloat> = reader.info().source_gamma;
            assert!(actual == expected);
        }
        trial("tests/pngsuite/f00n0g08.png", None);
        trial("tests/pngsuite/f00n2c08.png", None);
        trial("tests/pngsuite/f01n0g08.png", None);
        trial("tests/pngsuite/f01n2c08.png", None);
        trial("tests/pngsuite/f02n0g08.png", None);
        trial("tests/pngsuite/f02n2c08.png", None);
        trial("tests/pngsuite/f03n0g08.png", None);
        trial("tests/pngsuite/f03n2c08.png", None);
        trial("tests/pngsuite/f04n0g08.png", None);
        trial("tests/pngsuite/f04n2c08.png", None);
        trial("tests/pngsuite/f99n0g04.png", None);
        trial("tests/pngsuite/tm3n3p02.png", None);
        trial("tests/pngsuite/g03n0g16.png", Some(ScaledFloat::new(0.35)));
        trial("tests/pngsuite/g03n2c08.png", Some(ScaledFloat::new(0.35)));
        trial("tests/pngsuite/g03n3p04.png", Some(ScaledFloat::new(0.35)));
        trial("tests/pngsuite/g04n0g16.png", Some(ScaledFloat::new(0.45)));
        trial("tests/pngsuite/g04n2c08.png", Some(ScaledFloat::new(0.45)));
        trial("tests/pngsuite/g04n3p04.png", Some(ScaledFloat::new(0.45)));
        trial("tests/pngsuite/g05n0g16.png", Some(ScaledFloat::new(0.55)));
        trial("tests/pngsuite/g05n2c08.png", Some(ScaledFloat::new(0.55)));
        trial("tests/pngsuite/g05n3p04.png", Some(ScaledFloat::new(0.55)));
        trial("tests/pngsuite/g07n0g16.png", Some(ScaledFloat::new(0.7)));
        trial("tests/pngsuite/g07n2c08.png", Some(ScaledFloat::new(0.7)));
        trial("tests/pngsuite/g07n3p04.png", Some(ScaledFloat::new(0.7)));
        trial("tests/pngsuite/g10n0g16.png", Some(ScaledFloat::new(1.0)));
        trial("tests/pngsuite/g10n2c08.png", Some(ScaledFloat::new(1.0)));
        trial("tests/pngsuite/g10n3p04.png", Some(ScaledFloat::new(1.0)));
        trial("tests/pngsuite/g25n0g16.png", Some(ScaledFloat::new(2.5)));
        trial("tests/pngsuite/g25n2c08.png", Some(ScaledFloat::new(2.5)));
        trial("tests/pngsuite/g25n3p04.png", Some(ScaledFloat::new(2.5)));
        Ok(())
    }

    #[test]
    fn image_source_chromaticities() -> Result<(), ()> {
        fn trial(path: &str, expected: Option<SourceChromaticities>) {
            let decoder = crate::Decoder::new(File::open(path).unwrap());
            let reader = decoder.read_info().unwrap();
            let actual: Option<SourceChromaticities> = reader.info().source_chromaticities;
            assert!(actual == expected);
        }
        trial(
            "tests/pngsuite/ccwn2c08.png",
            Some(SourceChromaticities::new(
                (0.3127, 0.3290),
                (0.64, 0.33),
                (0.30, 0.60),
                (0.15, 0.06),
            )),
        );
        trial(
            "tests/pngsuite/ccwn3p08.png",
            Some(SourceChromaticities::new(
                (0.3127, 0.3290),
                (0.64, 0.33),
                (0.30, 0.60),
                (0.15, 0.06),
            )),
        );
        trial("tests/pngsuite/basi0g01.png", None);
        trial("tests/pngsuite/basi0g02.png", None);
        trial("tests/pngsuite/basi0g04.png", None);
        trial("tests/pngsuite/basi0g08.png", None);
        trial("tests/pngsuite/basi0g16.png", None);
        trial("tests/pngsuite/basi2c08.png", None);
        trial("tests/pngsuite/basi2c16.png", None);
        trial("tests/pngsuite/basi3p01.png", None);
        trial("tests/pngsuite/basi3p02.png", None);
        trial("tests/pngsuite/basi3p04.png", None);
        trial("tests/pngsuite/basi3p08.png", None);
        trial("tests/pngsuite/basi4a08.png", None);
        trial("tests/pngsuite/basi4a16.png", None);
        trial("tests/pngsuite/basi6a08.png", None);
        trial("tests/pngsuite/basi6a16.png", None);
        trial("tests/pngsuite/basn0g01.png", None);
        trial("tests/pngsuite/basn0g02.png", None);
        trial("tests/pngsuite/basn0g04.png", None);
        trial("tests/pngsuite/basn0g08.png", None);
        trial("tests/pngsuite/basn0g16.png", None);
        trial("tests/pngsuite/basn2c08.png", None);
        trial("tests/pngsuite/basn2c16.png", None);
        trial("tests/pngsuite/basn3p01.png", None);
        trial("tests/pngsuite/basn3p02.png", None);
        trial("tests/pngsuite/basn3p04.png", None);
        trial("tests/pngsuite/basn3p08.png", None);
        trial("tests/pngsuite/basn4a08.png", None);
        trial("tests/pngsuite/basn4a16.png", None);
        trial("tests/pngsuite/basn6a08.png", None);
        trial("tests/pngsuite/basn6a16.png", None);
        trial("tests/pngsuite/bgai4a08.png", None);
        trial("tests/pngsuite/bgai4a16.png", None);
        trial("tests/pngsuite/bgan6a08.png", None);
        trial("tests/pngsuite/bgan6a16.png", None);
        trial("tests/pngsuite/bgbn4a08.png", None);
        trial("tests/pngsuite/bggn4a16.png", None);
        trial("tests/pngsuite/bgwn6a08.png", None);
        trial("tests/pngsuite/bgyn6a16.png", None);
        trial("tests/pngsuite/cdfn2c08.png", None);
        trial("tests/pngsuite/cdhn2c08.png", None);
        trial("tests/pngsuite/cdsn2c08.png", None);
        trial("tests/pngsuite/cdun2c08.png", None);
        trial("tests/pngsuite/ch1n3p04.png", None);
        trial("tests/pngsuite/ch2n3p08.png", None);
        trial("tests/pngsuite/cm0n0g04.png", None);
        trial("tests/pngsuite/cm7n0g04.png", None);
        trial("tests/pngsuite/cm9n0g04.png", None);
        trial("tests/pngsuite/cs3n2c16.png", None);
        trial("tests/pngsuite/cs3n3p08.png", None);
        trial("tests/pngsuite/cs5n2c08.png", None);
        trial("tests/pngsuite/cs5n3p08.png", None);
        trial("tests/pngsuite/cs8n2c08.png", None);
        trial("tests/pngsuite/cs8n3p08.png", None);
        trial("tests/pngsuite/ct0n0g04.png", None);
        trial("tests/pngsuite/ct1n0g04.png", None);
        trial("tests/pngsuite/cten0g04.png", None);
        trial("tests/pngsuite/ctfn0g04.png", None);
        trial("tests/pngsuite/ctgn0g04.png", None);
        trial("tests/pngsuite/cthn0g04.png", None);
        trial("tests/pngsuite/ctjn0g04.png", None);
        trial("tests/pngsuite/ctzn0g04.png", None);
        trial("tests/pngsuite/f00n0g08.png", None);
        trial("tests/pngsuite/f00n2c08.png", None);
        trial("tests/pngsuite/f01n0g08.png", None);
        trial("tests/pngsuite/f01n2c08.png", None);
        trial("tests/pngsuite/f02n0g08.png", None);
        trial("tests/pngsuite/f02n2c08.png", None);
        trial("tests/pngsuite/f03n0g08.png", None);
        trial("tests/pngsuite/f03n2c08.png", None);
        trial("tests/pngsuite/f04n0g08.png", None);
        trial("tests/pngsuite/f04n2c08.png", None);
        trial("tests/pngsuite/f99n0g04.png", None);
        trial("tests/pngsuite/g03n0g16.png", None);
        trial("tests/pngsuite/g03n2c08.png", None);
        trial("tests/pngsuite/g03n3p04.png", None);
        trial("tests/pngsuite/g04n0g16.png", None);
        trial("tests/pngsuite/g04n2c08.png", None);
        trial("tests/pngsuite/g04n3p04.png", None);
        trial("tests/pngsuite/g05n0g16.png", None);
        trial("tests/pngsuite/g05n2c08.png", None);
        trial("tests/pngsuite/g05n3p04.png", None);
        trial("tests/pngsuite/g07n0g16.png", None);
        trial("tests/pngsuite/g07n2c08.png", None);
        trial("tests/pngsuite/g07n3p04.png", None);
        trial("tests/pngsuite/g10n0g16.png", None);
        trial("tests/pngsuite/g10n2c08.png", None);
        trial("tests/pngsuite/g10n3p04.png", None);
        trial("tests/pngsuite/g25n0g16.png", None);
        trial("tests/pngsuite/g25n2c08.png", None);
        trial("tests/pngsuite/g25n3p04.png", None);
        trial("tests/pngsuite/oi1n0g16.png", None);
        trial("tests/pngsuite/oi1n2c16.png", None);
        trial("tests/pngsuite/oi2n0g16.png", None);
        trial("tests/pngsuite/oi2n2c16.png", None);
        trial("tests/pngsuite/oi4n0g16.png", None);
        trial("tests/pngsuite/oi4n2c16.png", None);
        trial("tests/pngsuite/oi9n0g16.png", None);
        trial("tests/pngsuite/oi9n2c16.png", None);
        trial("tests/pngsuite/PngSuite.png", None);
        trial("tests/pngsuite/pp0n2c16.png", None);
        trial("tests/pngsuite/pp0n6a08.png", None);
        trial("tests/pngsuite/ps1n0g08.png", None);
        trial("tests/pngsuite/ps1n2c16.png", None);
        trial("tests/pngsuite/ps2n0g08.png", None);
        trial("tests/pngsuite/ps2n2c16.png", None);
        trial("tests/pngsuite/s01i3p01.png", None);
        trial("tests/pngsuite/s01n3p01.png", None);
        trial("tests/pngsuite/s02i3p01.png", None);
        trial("tests/pngsuite/s02n3p01.png", None);
        trial("tests/pngsuite/s03i3p01.png", None);
        trial("tests/pngsuite/s03n3p01.png", None);
        trial("tests/pngsuite/s04i3p01.png", None);
        trial("tests/pngsuite/s04n3p01.png", None);
        trial("tests/pngsuite/s05i3p02.png", None);
        trial("tests/pngsuite/s05n3p02.png", None);
        trial("tests/pngsuite/s06i3p02.png", None);
        trial("tests/pngsuite/s06n3p02.png", None);
        trial("tests/pngsuite/s07i3p02.png", None);
        trial("tests/pngsuite/s07n3p02.png", None);
        trial("tests/pngsuite/s08i3p02.png", None);
        trial("tests/pngsuite/s08n3p02.png", None);
        trial("tests/pngsuite/s09i3p02.png", None);
        trial("tests/pngsuite/s09n3p02.png", None);
        trial("tests/pngsuite/s32i3p04.png", None);
        trial("tests/pngsuite/s32n3p04.png", None);
        trial("tests/pngsuite/s33i3p04.png", None);
        trial("tests/pngsuite/s33n3p04.png", None);
        trial("tests/pngsuite/s34i3p04.png", None);
        trial("tests/pngsuite/s34n3p04.png", None);
        trial("tests/pngsuite/s35i3p04.png", None);
        trial("tests/pngsuite/s35n3p04.png", None);
        trial("tests/pngsuite/s36i3p04.png", None);
        trial("tests/pngsuite/s36n3p04.png", None);
        trial("tests/pngsuite/s37i3p04.png", None);
        trial("tests/pngsuite/s37n3p04.png", None);
        trial("tests/pngsuite/s38i3p04.png", None);
        trial("tests/pngsuite/s38n3p04.png", None);
        trial("tests/pngsuite/s39i3p04.png", None);
        trial("tests/pngsuite/s39n3p04.png", None);
        trial("tests/pngsuite/s40i3p04.png", None);
        trial("tests/pngsuite/s40n3p04.png", None);
        trial("tests/pngsuite/tbbn0g04.png", None);
        trial("tests/pngsuite/tbbn2c16.png", None);
        trial("tests/pngsuite/tbbn3p08.png", None);
        trial("tests/pngsuite/tbgn2c16.png", None);
        trial("tests/pngsuite/tbgn3p08.png", None);
        trial("tests/pngsuite/tbrn2c08.png", None);
        trial("tests/pngsuite/tbwn0g16.png", None);
        trial("tests/pngsuite/tbwn3p08.png", None);
        trial("tests/pngsuite/tbyn3p08.png", None);
        trial("tests/pngsuite/tm3n3p02.png", None);
        trial("tests/pngsuite/tp0n0g08.png", None);
        trial("tests/pngsuite/tp0n2c08.png", None);
        trial("tests/pngsuite/tp0n3p08.png", None);
        trial("tests/pngsuite/tp1n3p08.png", None);
        trial("tests/pngsuite/z00n2c08.png", None);
        trial("tests/pngsuite/z03n2c08.png", None);
        trial("tests/pngsuite/z06n2c08.png", None);
        Ok(())
    }

    #[test]
    fn image_source_sbit() {
        fn trial(path: &str, expected: Option<Cow<[u8]>>) {
            let decoder = crate::Decoder::new(File::open(path).unwrap());
            let reader = decoder.read_info().unwrap();
            let actual: Option<Cow<[u8]>> = reader.info().sbit.clone();
            assert!(actual == expected);
        }

        trial("tests/sbit/g.png", Some(Cow::Owned(vec![5u8])));
        trial("tests/sbit/ga.png", Some(Cow::Owned(vec![5u8, 3u8])));
        trial(
            "tests/sbit/indexed.png",
            Some(Cow::Owned(vec![5u8, 6u8, 5u8])),
        );
        trial("tests/sbit/rgb.png", Some(Cow::Owned(vec![5u8, 6u8, 5u8])));
        trial(
            "tests/sbit/rgba.png",
            Some(Cow::Owned(vec![5u8, 6u8, 5u8, 8u8])),
        );
    }

    /// Test handling of a PNG file that contains *two* iCCP chunks.
    /// This is a regression test for https://github.com/image-rs/image/issues/1825.
    #[test]
    fn test_two_iccp_chunks() {
        // The test file has been taken from
        // https://github.com/image-rs/image/issues/1825#issuecomment-1321798639,
        // but the 2nd iCCP chunk has been altered manually (see the 2nd comment below for more
        // details).
        let decoder = crate::Decoder::new(File::open("tests/bugfixes/issue#1825.png").unwrap());
        let reader = decoder.read_info().unwrap();
        let icc_profile = reader.info().icc_profile.clone().unwrap().into_owned();

        // Assert that the contents of the *first* iCCP chunk are returned.
        //
        // Note that the 2nd chunk in the test file has been manually altered to have a different
        // content (`b"test iccp contents"`) which would have a different CRC (797351983).
        assert_eq!(4070462061, crc32fast::hash(&icc_profile));
    }

    #[test]
    fn test_iccp_roundtrip() {
        let dummy_icc = b"I'm a profile";

        let mut info = crate::Info::with_size(1, 1);
        info.icc_profile = Some(dummy_icc.into());
        let mut encoded_image = Vec::new();
        let enc = crate::Encoder::with_info(&mut encoded_image, info).unwrap();
        let mut enc = enc.write_header().unwrap();
        enc.write_image_data(&[0]).unwrap();
        enc.finish().unwrap();

        let dec = crate::Decoder::new(encoded_image.as_slice());
        let dec = dec.read_info().unwrap();
        assert_eq!(dummy_icc, &**dec.info().icc_profile.as_ref().unwrap());
    }

    #[test]
    fn test_png_with_broken_iccp() {
        let decoder = crate::Decoder::new(File::open("tests/iccp/broken_iccp.png").unwrap());
        assert!(decoder.read_info().is_ok());
        let mut decoder = crate::Decoder::new(File::open("tests/iccp/broken_iccp.png").unwrap());
        decoder.set_ignore_iccp_chunk(true);
        assert!(decoder.read_info().is_ok());
    }

    /// Test handling of `mDCV` and `cLLI` chunks.`
    #[test]
    fn test_mdcv_and_clli_chunks() {
        let decoder = crate::Decoder::new(File::open("tests/bugfixes/cicp_pq.png").unwrap());
        let reader = decoder.read_info().unwrap();
        let info = reader.info();

        let cicp = info.coding_independent_code_points.unwrap();
        assert_eq!(cicp.color_primaries, 9);
        assert_eq!(cicp.transfer_function, 16);
        assert_eq!(cicp.matrix_coefficients, 0);
        assert!(cicp.is_video_full_range_image);

        let mdcv = info.mastering_display_color_volume.unwrap();
        assert_relative_eq!(mdcv.chromaticities.red.0.into_value(), 0.680);
        assert_relative_eq!(mdcv.chromaticities.red.1.into_value(), 0.320);
        assert_relative_eq!(mdcv.chromaticities.green.0.into_value(), 0.265);
        assert_relative_eq!(mdcv.chromaticities.green.1.into_value(), 0.690);
        assert_relative_eq!(mdcv.chromaticities.blue.0.into_value(), 0.150);
        assert_relative_eq!(mdcv.chromaticities.blue.1.into_value(), 0.060);
        assert_relative_eq!(mdcv.chromaticities.white.0.into_value(), 0.3127);
        assert_relative_eq!(mdcv.chromaticities.white.1.into_value(), 0.3290);
        assert_relative_eq!(mdcv.min_luminance as f32 / 10_000.0, 0.01);
        assert_relative_eq!(mdcv.max_luminance as f32 / 10_000.0, 5000.0);

        let clli = info.content_light_level.unwrap();
        assert_relative_eq!(clli.max_content_light_level as f32 / 10_000.0, 4000.0);
        assert_relative_eq!(clli.max_frame_average_light_level as f32 / 10_000.0, 2627.0);
    }

    /// Tests what happens then [`Reader.finish`] is called twice.
    #[test]
    fn test_finishing_twice() {
        let mut png = Vec::new();
        write_noncompressed_png(&mut png, 16, 1024);
        let decoder = Decoder::new(png.as_slice());
        let mut reader = decoder.read_info().unwrap();

        // First call to `finish` - expecting success.
        reader.finish().unwrap();

        // Second call to `finish` - expecting an error.
        let err = reader.finish().unwrap_err();
        assert!(matches!(&err, DecodingError::Parameter(_)));
        assert_eq!("End of image has been reached", format!("{err}"));
    }

    /// Writes an acTL chunk.
    /// See https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk
    fn write_actl(w: &mut impl Write, animation: &crate::AnimationControl) {
        let mut data = Vec::new();
        data.write_u32::<byteorder::BigEndian>(animation.num_frames)
            .unwrap();
        data.write_u32::<byteorder::BigEndian>(animation.num_plays)
            .unwrap();
        write_chunk(w, b"acTL", &data);
    }

    /// Writes an fcTL chunk.
    /// See https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk
    fn write_fctl(w: &mut impl Write, frame: &crate::FrameControl) {
        let mut data = Vec::new();
        data.write_u32::<byteorder::BigEndian>(frame.sequence_number)
            .unwrap();
        data.write_u32::<byteorder::BigEndian>(frame.width).unwrap();
        data.write_u32::<byteorder::BigEndian>(frame.height)
            .unwrap();
        data.write_u32::<byteorder::BigEndian>(frame.x_offset)
            .unwrap();
        data.write_u32::<byteorder::BigEndian>(frame.y_offset)
            .unwrap();
        data.write_u16::<byteorder::BigEndian>(frame.delay_num)
            .unwrap();
        data.write_u16::<byteorder::BigEndian>(frame.delay_den)
            .unwrap();
        data.write_u8(frame.dispose_op as u8).unwrap();
        data.write_u8(frame.blend_op as u8).unwrap();
        write_chunk(w, b"fcTL", &data);
    }

    /// Writes an fdAT chunk.
    /// See https://wiki.mozilla.org/APNG_Specification#.60fdAT.60:_The_Frame_Data_Chunk
    fn write_fdat(w: &mut impl Write, sequence_number: u32, image_data: &[u8]) {
        let mut data = Vec::new();
        data.write_u32::<byteorder::BigEndian>(sequence_number)
            .unwrap();
        data.write_all(image_data).unwrap();
        write_chunk(w, b"fdAT", &data);
    }

    /// Writes PNG signature and chunks that can precede an fdAT chunk that is expected
    /// to have
    /// - `sequence_number` set to 0
    /// - image data with rgba8 pixels in a `width` by `width` image
    fn write_fdat_prefix(w: &mut impl Write, num_frames: u32, width: u32) {
        write_png_sig(w);
        write_rgba8_ihdr_with_width(w, width);
        write_actl(
            w,
            &crate::AnimationControl {
                num_frames,
                num_plays: 0,
            },
        );

        let mut fctl = crate::FrameControl {
            width,
            height: width,
            ..Default::default()
        };
        write_fctl(w, &fctl);
        write_rgba8_idats(w, width, 0x7fffffff);

        fctl.sequence_number += 1;
        write_fctl(w, &fctl);
    }

    #[test]
    fn test_fdat_chunk_payload_length_0() {
        let mut png = Vec::new();
        write_fdat_prefix(&mut png, 2, 8);
        write_chunk(&mut png, b"fdAT", &[]);

        let decoder = Decoder::new(png.as_slice());
        let mut reader = decoder.read_info().unwrap();
        let mut buf = vec![0; reader.output_buffer_size()];
        reader.next_frame(&mut buf).unwrap();

        // 0-length fdAT should result in an error.
        let err = reader.next_frame(&mut buf).unwrap_err();
        assert!(matches!(&err, DecodingError::Format(_)));
        assert_eq!("fdAT chunk shorter than 4 bytes", format!("{err}"));

        // Calling `next_frame` again should return an error.  Same error as above would be nice,
        // but it is probably unnecessary and infeasible (`DecodingError` can't derive `Clone`
        // because `std::io::Error` doesn't implement `Clone`)..  But it definitely shouldn't enter
        // an infinite loop.
        let err2 = reader.next_frame(&mut buf).unwrap_err();
        assert!(matches!(&err2, DecodingError::Parameter(_)));
        assert_eq!(
            "A fatal decoding error has been encounted earlier",
            format!("{err2}")
        );
    }

    #[test]
    fn test_fdat_chunk_payload_length_3() {
        let mut png = Vec::new();
        write_fdat_prefix(&mut png, 2, 8);
        write_chunk(&mut png, b"fdAT", &[1, 0, 0]);

        let decoder = Decoder::new(png.as_slice());
        let mut reader = decoder.read_info().unwrap();
        let mut buf = vec![0; reader.output_buffer_size()];
        reader.next_frame(&mut buf).unwrap();

        // 3-bytes-long fdAT should result in an error.
        let err = reader.next_frame(&mut buf).unwrap_err();
        assert!(matches!(&err, DecodingError::Format(_)));
        assert_eq!("fdAT chunk shorter than 4 bytes", format!("{err}"));
    }

    #[test]
    fn test_frame_split_across_two_fdat_chunks() {
        // Generate test data where the 2nd animation frame is split across 2 fdAT chunks.
        //
        // This is similar to the example given in
        // https://wiki.mozilla.org/APNG_Specification#Chunk_Sequence_Numbers:
        //
        // ```
        //    Sequence number    Chunk
        //    (none)             `acTL`
        //    0                  `fcTL` first frame
        //    (none)             `IDAT` first frame / default image
        //    1                  `fcTL` second frame
        //    2                  first `fdAT` for second frame
        //    3                  second `fdAT` for second frame
        // ```
        let png = {
            let mut png = Vec::new();
            write_fdat_prefix(&mut png, 2, 8);
            let image_data = generate_rgba8_with_width_and_height(8, 8);
            write_fdat(&mut png, 2, &image_data[..30]);
            write_fdat(&mut png, 3, &image_data[30..]);
            write_iend(&mut png);
            png
        };

        // Start decoding.
        let decoder = Decoder::new(png.as_slice());
        let mut reader = decoder.read_info().unwrap();
        let mut buf = vec![0; reader.output_buffer_size()];
        let Some(animation_control) = reader.info().animation_control else {
            panic!("No acTL");
        };
        assert_eq!(animation_control.num_frames, 2);

        // Process the 1st animation frame.
        let first_frame: Vec<u8>;
        {
            reader.next_frame(&mut buf).unwrap();
            first_frame = buf.clone();

            // Note that the doc comment of `Reader::next_frame` says that "[...]
            // can be checked afterwards by calling `info` **after** a successful call and
            // inspecting the `frame_control` data.".  (Note the **emphasis** on "after".)
            let Some(frame_control) = reader.info().frame_control else {
                panic!("No fcTL (1st frame)");
            };
            // The sequence number is taken from the `fcTL` chunk that comes before the `IDAT`
            // chunk.
            assert_eq!(frame_control.sequence_number, 0);
        }

        // Process the 2nd animation frame.
        let second_frame: Vec<u8>;
        {
            reader.next_frame(&mut buf).unwrap();
            second_frame = buf.clone();

            // Same as above - updated `frame_control` is available *after* the `next_frame` call.
            let Some(frame_control) = reader.info().frame_control else {
                panic!("No fcTL (2nd frame)");
            };
            // The sequence number is taken from the `fcTL` chunk that comes before the two `fdAT`
            // chunks.  Note that sequence numbers inside `fdAT` chunks are not publicly exposed
            // (but they are still checked when decoding to verify that they are sequential).
            assert_eq!(frame_control.sequence_number, 1);
        }

        assert_eq!(first_frame, second_frame);
    }

    #[test]
    fn test_idat_bigger_than_image_size_from_ihdr() {
        let png = {
            let mut png = Vec::new();
            write_png_sig(&mut png);
            write_rgba8_ihdr_with_width(&mut png, 8);

            // Here we want to test an invalid image where the `IDAT` chunk contains more data
            // (data for 8x256 image) than declared in the `IHDR` chunk (which only describes an
            // 8x8 image).
            write_chunk(
                &mut png,
                b"IDAT",
                &generate_rgba8_with_width_and_height(8, 256),
            );

            write_iend(&mut png);
            png
        };
        let decoder = Decoder::new(png.as_slice());
        let mut reader = decoder.read_info().unwrap();
        let mut buf = vec![0; reader.output_buffer_size()];

        // TODO: Should this return an error instead?  For now let's just have test assertions for
        // the current behavior.
        reader.next_frame(&mut buf).unwrap();
        assert_eq!(3093270825, crc32fast::hash(&buf));
    }

    #[test]
    fn test_only_idat_chunk_in_input_stream() {
        let png = {
            let mut png = Vec::new();
            write_png_sig(&mut png);
            write_chunk(&mut png, b"IDAT", &[]);
            png
        };
        let decoder = Decoder::new(png.as_slice());
        let Err(err) = decoder.read_info() else {
            panic!("Expected an error")
        };
        assert!(matches!(&err, DecodingError::Format(_)));
        assert_eq!(
            "ChunkType { type: IDAT, \
                         critical: true, \
                         private: false, \
                         reserved: false, \
                         safecopy: false \
             } chunk appeared before IHDR chunk",
            format!("{err}"),
        );
    }

    /// `StreamingInput` can be used by tests to simulate a streaming input
    /// (e.g. a slow http response, where all bytes are not immediately available).
    #[derive(Clone)]
    struct StreamingInput(Rc<RefCell<StreamingInputState>>);

    struct StreamingInputState {
        full_input: Vec<u8>,
        current_pos: usize,
        available_len: usize,
    }

    impl StreamingInput {
        fn new(full_input: Vec<u8>) -> Self {
            Self(Rc::new(RefCell::new(StreamingInputState {
                full_input,
                current_pos: 0,
                available_len: 0,
            })))
        }

        fn with_noncompressed_png(width: u32, idat_size: usize) -> Self {
            let mut png = Vec::new();
            write_noncompressed_png(&mut png, width, idat_size);
            Self::new(png)
        }

        fn expose_next_byte(&self) {
            let mut state = self.0.borrow_mut();
            assert!(state.available_len < state.full_input.len());
            state.available_len += 1;
        }

        fn stream_input_until_reader_is_available(&self) -> Reader<StreamingInput> {
            loop {
                self.0.borrow_mut().current_pos = 0;
                match Decoder::new(self.clone()).read_info() {
                    Ok(reader) => {
                        break reader;
                    }
                    Err(DecodingError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => {
                        self.expose_next_byte();
                    }
                    _ => panic!("Unexpected error"),
                }
            }
        }

        fn decode_full_input<F, R>(&self, f: F) -> R
        where
            F: FnOnce(Reader<&[u8]>) -> R,
        {
            let state = self.0.borrow();
            let decoder = Decoder::new(state.full_input.as_slice());
            f(decoder.read_info().unwrap())
        }
    }

    impl Read for StreamingInput {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let mut state = self.0.borrow_mut();
            let mut available_bytes = &state.full_input[state.current_pos..state.available_len];
            let number_of_read_bytes = available_bytes.read(buf)?;
            state.current_pos += number_of_read_bytes;
            assert!(state.current_pos <= state.available_len);
            Ok(number_of_read_bytes)
        }
    }

    /// Test resuming/retrying `Reader.next_frame` after `UnexpectedEof`.
    #[test]
    fn test_streaming_input_and_decoding_via_next_frame() {
        const WIDTH: u32 = 16;
        const IDAT_SIZE: usize = 512;
        let streaming_input = StreamingInput::with_noncompressed_png(WIDTH, IDAT_SIZE);

        let (whole_output_info, decoded_from_whole_input) =
            streaming_input.decode_full_input(|mut r| {
                let mut buf = vec![0; r.output_buffer_size()];
                let output_info = r.next_frame(&mut buf).unwrap();
                (output_info, buf)
            });

        let mut png_reader = streaming_input.stream_input_until_reader_is_available();
        let mut decoded_from_streaming_input = vec![0; png_reader.output_buffer_size()];
        let streaming_output_info = loop {
            match png_reader.next_frame(decoded_from_streaming_input.as_mut_slice()) {
                Ok(output_info) => break output_info,
                Err(DecodingError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => {
                    streaming_input.expose_next_byte()
                }
                e => panic!("Unexpected error: {:?}", e),
            }
        };
        assert_eq!(whole_output_info, streaming_output_info);
        assert_eq!(
            crc32fast::hash(&decoded_from_whole_input),
            crc32fast::hash(&decoded_from_streaming_input)
        );
    }

    /// Test resuming/retrying `Reader.next_row` after `UnexpectedEof`.
    #[test]
    fn test_streaming_input_and_decoding_via_next_row() {
        const WIDTH: u32 = 16;
        const IDAT_SIZE: usize = 512;
        let streaming_input = StreamingInput::with_noncompressed_png(WIDTH, IDAT_SIZE);

        let decoded_from_whole_input = streaming_input.decode_full_input(|mut r| {
            let mut buf = vec![0; r.output_buffer_size()];
            r.next_frame(&mut buf).unwrap();
            buf
        });

        let mut png_reader = streaming_input.stream_input_until_reader_is_available();
        let mut decoded_from_streaming_input = Vec::new();
        loop {
            match png_reader.next_row() {
                Ok(None) => break,
                Ok(Some(row)) => decoded_from_streaming_input.extend_from_slice(row.data()),
                Err(DecodingError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => {
                    streaming_input.expose_next_byte()
                }
                e => panic!("Unexpected error: {:?}", e),
            }
        }
        assert_eq!(
            crc32fast::hash(&decoded_from_whole_input),
            crc32fast::hash(&decoded_from_streaming_input)
        );
    }

    /// Test resuming/retrying `Decoder.read_header_info` after `UnexpectedEof`.
    #[test]
    fn test_streaming_input_and_reading_header_info() {
        const WIDTH: u32 = 16;
        const IDAT_SIZE: usize = 512;
        let streaming_input = StreamingInput::with_noncompressed_png(WIDTH, IDAT_SIZE);

        let info_from_whole_input = streaming_input.decode_full_input(|r| r.info().clone());

        let mut decoder = Decoder::new(streaming_input.clone());
        let info_from_streaming_input = loop {
            match decoder.read_header_info() {
                Ok(info) => break info.clone(),
                Err(DecodingError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => {
                    streaming_input.expose_next_byte()
                }
                e => panic!("Unexpected error: {:?}", e),
            }
        };

        assert_eq!(info_from_whole_input.width, info_from_streaming_input.width);
        assert_eq!(
            info_from_whole_input.height,
            info_from_streaming_input.height
        );
        assert_eq!(
            info_from_whole_input.bit_depth,
            info_from_streaming_input.bit_depth
        );
        assert_eq!(
            info_from_whole_input.color_type,
            info_from_streaming_input.color_type
        );
        assert_eq!(
            info_from_whole_input.interlaced,
            info_from_streaming_input.interlaced
        );
    }

    /// Creates a ready-to-test [`Reader`] which decodes a PNG that contains:
    /// IHDR, IDAT, IEND.
    fn create_reader_of_ihdr_idat() -> Reader<VecDeque<u8>> {
        let mut png = VecDeque::new();
        write_noncompressed_png(&mut png, /* width = */ 16, /* idat_size = */ 1024);
        Decoder::new(png).read_info().unwrap()
    }

    /// Creates a ready-to-test [`Reader`] which decodes an animated PNG that contains:
    /// IHDR, acTL, fcTL, IDAT, fcTL, fdAT, IEND.  (i.e. IDAT is part of the animation)
    fn create_reader_of_ihdr_actl_fctl_idat_fctl_fdat() -> Reader<VecDeque<u8>> {
        let idat_width = 16;
        let mut fctl = crate::FrameControl {
            width: idat_width,
            height: idat_width, // same height and width
            ..Default::default()
        };

        let mut png = VecDeque::new();
        write_png_sig(&mut png);
        write_rgba8_ihdr_with_width(&mut png, idat_width);
        write_actl(
            &mut png,
            &crate::AnimationControl {
                num_frames: 2,
                num_plays: 0,
            },
        );
        fctl.sequence_number = 0;
        write_fctl(&mut png, &fctl);
        // Using `fctl.height + 1` means that the `IDAT` will have "left-over" data after
        // processing.  This helps to verify that `Reader.read_until_image_data` discards the
        // left-over data when resetting `UnfilteredRowsBuffer`.
        let idat_data = generate_rgba8_with_width_and_height(fctl.width, fctl.height + 1);
        write_chunk(&mut png, b"IDAT", &idat_data);

        let fdat_width = 10;
        fctl.sequence_number = 1;
        // Using different width in `IDAT` and `fDAT` frames helps to catch problems that
        // may arise when `Reader.read_until_image_data` doesn't properly reset
        // `UnfilteredRowsBuffer`.
        fctl.width = fdat_width;
        write_fctl(&mut png, &fctl);
        let fdat_data = generate_rgba8_with_width_and_height(fctl.width, fctl.height);
        write_fdat(&mut png, 2, &fdat_data);
        write_iend(&mut png);

        Decoder::new(png).read_info().unwrap()
    }

    /// Creates a ready-to-test [`Reader`] which decodes an animated PNG that contains: IHDR, acTL,
    /// IDAT, fcTL, fdAT, fcTL, fdAT, IEND.  (i.e. IDAT is *not* part of the animation)
    fn create_reader_of_ihdr_actl_idat_fctl_fdat_fctl_fdat() -> Reader<VecDeque<u8>> {
        let width = 16;
        let frame_data = generate_rgba8_with_width_and_height(width, width);
        let mut fctl = crate::FrameControl {
            width,
            height: width,
            ..Default::default()
        };

        let mut png = VecDeque::new();
        write_png_sig(&mut png);
        write_rgba8_ihdr_with_width(&mut png, width);
        write_actl(
            &mut png,
            &crate::AnimationControl {
                num_frames: 2,
                num_plays: 0,
            },
        );
        write_chunk(&mut png, b"IDAT", &frame_data);
        fctl.sequence_number = 0;
        write_fctl(&mut png, &fctl);
        write_fdat(&mut png, 1, &frame_data);
        fctl.sequence_number = 2;
        write_fctl(&mut png, &fctl);
        write_fdat(&mut png, 3, &frame_data);
        write_iend(&mut png);

        Decoder::new(png).read_info().unwrap()
    }

    fn get_fctl_sequence_number(reader: &Reader<impl Read>) -> u32 {
        reader
            .info()
            .frame_control
            .as_ref()
            .unwrap()
            .sequence_number
    }

    /// Tests that [`Reader.next_frame`] will report a `PolledAfterEndOfImage` error when called
    /// after already decoding a single frame in a non-animated PNG.
    #[test]
    fn test_next_frame_polling_after_end_non_animated() {
        let mut reader = create_reader_of_ihdr_idat();
        let mut buf = vec![0; reader.output_buffer_size()];
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for IDAT frame");

        let err = reader
            .next_frame(&mut buf)
            .expect_err("Main test - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }

    /// Tests that [`Reader.next_frame_info`] will report a `PolledAfterEndOfImage` error when
    /// called when decoding a PNG that only contains a single frame.
    #[test]
    fn test_next_frame_info_polling_after_end_non_animated() {
        let mut reader = create_reader_of_ihdr_idat();

        let err = reader
            .next_frame_info()
            .expect_err("Main test - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }

    /// Tests that [`Reader.next_frame`] will report a `PolledAfterEndOfImage` error when called
    /// after already decoding a single frame in an animated PNG where IDAT is part of the
    /// animation.
    #[test]
    fn test_next_frame_polling_after_end_idat_part_of_animation() {
        let mut reader = create_reader_of_ihdr_actl_fctl_idat_fctl_fdat();
        let mut buf = vec![0; reader.output_buffer_size()];

        assert_eq!(get_fctl_sequence_number(&reader), 0);
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for IDAT frame");

        // `next_frame` doesn't advance to the next `fcTL`.
        assert_eq!(get_fctl_sequence_number(&reader), 0);

        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for fdAT frame");
        assert_eq!(get_fctl_sequence_number(&reader), 1);

        let err = reader
            .next_frame(&mut buf)
            .expect_err("Main test - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }

    /// Tests that [`Reader.next_frame`] will report a `PolledAfterEndOfImage` error when called
    /// after already decoding a single frame in an animated PNG where IDAT is *not* part of the
    /// animation.
    #[test]
    fn test_next_frame_polling_after_end_idat_not_part_of_animation() {
        let mut reader = create_reader_of_ihdr_actl_idat_fctl_fdat_fctl_fdat();
        let mut buf = vec![0; reader.output_buffer_size()];

        assert!(reader.info().frame_control.is_none());
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for IDAT frame");

        // `next_frame` doesn't advance to the next `fcTL`.
        assert!(reader.info().frame_control.is_none());

        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for 1st fdAT frame");
        assert_eq!(get_fctl_sequence_number(&reader), 0);

        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for 2nd fdAT frame");
        assert_eq!(get_fctl_sequence_number(&reader), 2);

        let err = reader
            .next_frame(&mut buf)
            .expect_err("Main test - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }

    /// Tests that after decoding a whole frame via [`Reader.next_row`] the call to
    /// [`Reader.next_frame`] will decode the **next** frame.
    #[test]
    fn test_row_by_row_then_next_frame() {
        let mut reader = create_reader_of_ihdr_actl_fctl_idat_fctl_fdat();
        let mut buf = vec![0; reader.output_buffer_size()];

        assert_eq!(get_fctl_sequence_number(&reader), 0);
        while let Some(_) = reader.next_row().unwrap() {}
        assert_eq!(get_fctl_sequence_number(&reader), 0);

        buf.fill(0x0f);
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error from next_frame call");

        // Verify if we have read the next `fcTL` chunk + repopulated `buf`:
        assert_eq!(get_fctl_sequence_number(&reader), 1);
        assert!(buf.iter().any(|byte| *byte != 0x0f));
    }

    /// Tests that after decoding a whole frame via [`Reader.next_row`] it is possible
    /// to use [`Reader.next_row`] to decode the next frame (by using the `next_frame_info` API to
    /// advance to the next frame when `next_row` returns `None`).
    #[test]
    fn test_row_by_row_of_two_frames() {
        let mut reader = create_reader_of_ihdr_actl_fctl_idat_fctl_fdat();

        let mut rows_of_frame1 = 0;
        assert_eq!(get_fctl_sequence_number(&reader), 0);
        while let Some(_) = reader.next_row().unwrap() {
            rows_of_frame1 += 1;
        }
        assert_eq!(rows_of_frame1, 16);
        assert_eq!(get_fctl_sequence_number(&reader), 0);

        let mut rows_of_frame2 = 0;
        assert_eq!(reader.next_frame_info().unwrap().sequence_number, 1);
        assert_eq!(get_fctl_sequence_number(&reader), 1);
        while let Some(_) = reader.next_row().unwrap() {
            rows_of_frame2 += 1;
        }
        assert_eq!(rows_of_frame2, 16);
        assert_eq!(get_fctl_sequence_number(&reader), 1);

        let err = reader
            .next_frame_info()
            .expect_err("No more frames - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }

    /// This test is similar to `test_next_frame_polling_after_end_idat_part_of_animation`, but it
    /// uses `next_frame_info` calls to read to the next `fcTL` earlier - before the next call to
    /// `next_frame` (knowing `fcTL` before calling `next_frame` may be helpful to determine the
    /// size of the output buffer and/or to prepare the buffer based on the `DisposeOp` of the
    /// previous frames).
    #[test]
    fn test_next_frame_info_after_next_frame() {
        let mut reader = create_reader_of_ihdr_actl_fctl_idat_fctl_fdat();
        let mut buf = vec![0; reader.output_buffer_size()];

        assert_eq!(get_fctl_sequence_number(&reader), 0);
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for IDAT frame");

        // `next_frame` doesn't advance to the next `fcTL`.
        assert_eq!(get_fctl_sequence_number(&reader), 0);

        // But `next_frame_info` can be used to go to the next `fcTL`.
        assert_eq!(reader.next_frame_info().unwrap().sequence_number, 1);
        assert_eq!(get_fctl_sequence_number(&reader), 1);

        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for fdAT frame");
        assert_eq!(get_fctl_sequence_number(&reader), 1);

        let err = reader
            .next_frame_info()
            .expect_err("Main test - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }

    /// This test is similar to `test_next_frame_polling_after_end_idat_not_part_of_animation`, but
    /// it uses `next_frame_info` to skip the `IDAT` frame entirely + to move between frames.
    #[test]
    fn test_next_frame_info_to_skip_first_frame() {
        let mut reader = create_reader_of_ihdr_actl_idat_fctl_fdat_fctl_fdat();
        let mut buf = vec![0; reader.output_buffer_size()];

        // First (IDAT) frame doesn't have frame control info, which means
        // that it is not part of the animation.
        assert!(reader.info().frame_control.is_none());

        // `next_frame_info` can be used to skip the IDAT frame (without first having to separately
        // discard the image data - e.g. by also calling `next_frame` first).
        assert_eq!(reader.next_frame_info().unwrap().sequence_number, 0);
        assert_eq!(get_fctl_sequence_number(&reader), 0);
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for 1st fdAT frame");
        assert_eq!(get_fctl_sequence_number(&reader), 0);

        // Get the `fcTL` for the 2nd frame.
        assert_eq!(reader.next_frame_info().unwrap().sequence_number, 2);
        reader
            .next_frame(&mut buf)
            .expect("Expecting no error for 2nd fdAT frame");
        assert_eq!(get_fctl_sequence_number(&reader), 2);

        let err = reader
            .next_frame_info()
            .expect_err("Main test - expecting error");
        assert!(
            matches!(&err, DecodingError::Parameter(_)),
            "Unexpected kind of error: {:?}",
            &err,
        );
    }
}