ggstd 0.1.0

Partial implementation of Go standard library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
// Copyright 2023 The rust-ggstd authors. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

use super::paeth::filter_paeth;
use crate::compat;
use crate::compress::zlib;
use crate::encoding::binary::{self, ByteOrder};
use crate::hash::{crc32, Hash, Hash32};
use crate::image::{
    self,
    color::{self, Color, Gray, Gray16, Model, Palette, RGBA},
    Image, Img,
};
use std::io::Read;
use std::io::Write;

/// Color type, as per the PNG spec.
pub(super) enum ColorType {
    Grayscale = 0,
    TrueColor = 2,
    Paletted = 3,
    GrayscaleAlpha = 4,
    TrueColorAlpha = 6,
}

impl ColorType {
    fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ColorType::Grayscale),
            2 => Some(ColorType::TrueColor),
            3 => Some(ColorType::Paletted),
            4 => Some(ColorType::GrayscaleAlpha),
            6 => Some(ColorType::TrueColorAlpha),
            _ => None,
        }
    }
}

/// A CB is a combination of color type and bit depth.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(super) enum CB {
    G1,
    G2,
    G4,
    G8,
    GA8,
    TC8,
    P1,
    P2,
    P4,
    P8,
    TCA8,
    G16,
    GA16,
    TC16,
    TCA16,
}

impl CB {
    pub(super) fn paletted(self) -> bool {
        matches!(self, CB::P1 | CB::P2 | CB::P4 | CB::P8)
    }

    pub(super) fn true_color(&self) -> bool {
        matches!(self, CB::TC8 | CB::TC16)
    }
}

/// Filter type, as per the PNG spec.
#[derive(Debug)]
pub(super) enum FilterType {
    None = 0,
    Sub = 1,
    Up = 2,
    Average = 3,
    Paeth = 4,
}

const FT_NONE: u8 = FilterType::None as u8;
const FT_SUB: u8 = FilterType::Sub as u8;
const FT_UP: u8 = FilterType::Up as u8;
const FT_AVERAGE: u8 = FilterType::Average as u8;
const FT_PAETH: u8 = FilterType::Paeth as u8;

/// Interlace type.
#[derive(Debug, PartialEq, Copy, Clone)]
enum InterlaceType {
    None = 0,
    Adam7 = 1,
}

/// InterlaceScan defines the placement and size of a pass for Adam7 interlacing.
struct InterlaceScan {
    x_factor: isize,
    y_factor: isize,
    x_offset: isize,
    y_offset: isize,
}

impl InterlaceScan {
    const fn new(xf: isize, yf: isize, xo: isize, yo: isize) -> Self {
        Self {
            x_factor: xf,
            y_factor: yf,
            x_offset: xo,
            y_offset: yo,
        }
    }
}

/// INTERLACING defines Adam7 interlacing, with 7 passes of reduced images.
/// See <https://www.w3.org/TR/PNG/#8Interlace>
const INTERLACING: &[InterlaceScan] = &[
    InterlaceScan::new(8, 8, 0, 0),
    InterlaceScan::new(8, 8, 4, 0),
    InterlaceScan::new(4, 8, 0, 4),
    InterlaceScan::new(4, 4, 2, 0),
    InterlaceScan::new(2, 4, 0, 2),
    InterlaceScan::new(2, 2, 1, 0),
    InterlaceScan::new(1, 2, 0, 1),
];

/// Decoding stage.
/// The PNG specification says that the IHDR, PLTE (if present), tRNS (if
/// present), IDAT and IEND chunks must appear in that order. There may be
/// multiple IDAT chunks, and IDAT chunks must be sequential (i.e. they may not
/// have any other chunks between them).
/// <https://www.w3.org/TR/PNG/#5ChunkOrdering>
#[derive(PartialEq, PartialOrd)]
enum DecodingStage {
    Start = 0,
    SeenIHDR,
    SeenPLTE,
    SeentRNS,
    SeenIDAT,
    SeenIEND,
}

pub(super) const PNG_HEADER: &[u8] = b"\x89PNG\r\n\x1a\n";

struct Decoder {
    img: Option<Box<Img>>,
    crc: crc32::Digest<'static>,
    width: usize,
    height: usize,
    depth: u8,
    palette_vec: Vec<Color>,
    palette: Option<Palette>,
    cb: CB,
    stage: DecodingStage,
    interlace: InterlaceType,
    // use_transparent and transparent are used for grayscale and truecolor
    // transparency, as opposed to palette transparency.
    use_transparent: bool,
    transparent: [u8; 6],
}

impl Default for Decoder {
    fn default() -> Self {
        Self {
            width: 0,
            height: 0,
            stage: DecodingStage::Start,
            crc: crc32::new_ieee(),
            depth: 0,
            cb: CB::TC8, // placeholder until the header is decoded
            interlace: InterlaceType::None,
            use_transparent: false,
            transparent: [0; 6],
            img: None,
            palette_vec: Vec::with_capacity(0),
            palette: None,
        }
    }
}

#[derive(Debug)]
pub enum Error {
    /// A FormatError reports that the input is not a valid PNG.
    FormatError(String),
    /// Input-output error
    StdIo(std::io::Error),
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Error::StdIo(error)
    }
}

impl Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::FormatError(v) => write!(f, "FormatError({})", v),
            Error::StdIo(v) => write!(f, "{}", v),
        }
    }
}

impl std::error::Error for Error {}

fn new_chunk_order_error() -> std::io::Error {
    new_format_error("chunk out of order")
}

fn new_unsupported_error(msg: &str) -> std::io::Error {
    new_format_error(&format!("png: unsupported feature: {}", msg))
}

fn new_format_error(message: &str) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidData, message.to_string())
}

fn decode_cb(depth: u8, color_type: u8) -> std::io::Result<CB> {
    let ct = match ColorType::from_u8(color_type) {
        Some(ct) => ct,
        None => return Err(new_unsupported_error(&format!("color type {}", color_type))),
    };
    match depth {
        1 => match ct {
            ColorType::Grayscale => return Ok(CB::G1),
            ColorType::Paletted => return Ok(CB::P1),
            _ => {}
        },
        2 => match ct {
            ColorType::Grayscale => return Ok(CB::G2),
            ColorType::Paletted => return Ok(CB::P2),
            _ => {}
        },
        4 => match ct {
            ColorType::Grayscale => return Ok(CB::G4),
            ColorType::Paletted => return Ok(CB::P4),
            _ => {}
        },
        8 => match ct {
            ColorType::Grayscale => return Ok(CB::G8),
            ColorType::TrueColor => return Ok(CB::TC8),
            ColorType::Paletted => return Ok(CB::P8),
            ColorType::GrayscaleAlpha => return Ok(CB::GA8),
            ColorType::TrueColorAlpha => return Ok(CB::TCA8),
        },
        16 => match ct {
            ColorType::Grayscale => return Ok(CB::G16),
            ColorType::TrueColor => return Ok(CB::TC16),
            ColorType::GrayscaleAlpha => return Ok(CB::GA16),
            ColorType::TrueColorAlpha => return Ok(CB::TCA16),
            _ => {}
        },
        _ => {}
    }
    Err(new_unsupported_error(&format!(
        "bit depth {}, color type {}",
        depth, color_type
    )))
}

impl Decoder {
    fn parse_ihdr<Input: std::io::BufRead>(
        &mut self,
        r: &mut Input,
        length: u32,
    ) -> std::io::Result<()> {
        if length != 13 {
            return Err(new_format_error("bad IHDR length"));
        }
        let mut tmp = [0; 13];
        r.read_exact(&mut tmp)?;
        self.crc.write_all(&tmp[..13])?;
        if tmp[10] != 0 {
            return Err(new_unsupported_error("compression method"));
        }
        if tmp[11] != 0 {
            return Err(new_unsupported_error("filter method"));
        }
        const IT_NONE: u8 = InterlaceType::None as u8;
        const IT_ADAM7: u8 = InterlaceType::Adam7 as u8;
        self.interlace = match tmp[12] {
            IT_NONE => InterlaceType::None,
            IT_ADAM7 => InterlaceType::Adam7,
            _ => return Err(new_format_error("invalid interlace method")),
        };

        let w = binary::BIG_ENDIAN.uint32(&tmp[0..4]) as i32;
        let h = binary::BIG_ENDIAN.uint32(&tmp[4..8]) as i32;
        if w <= 0 || h <= 0 {
            return Err(new_format_error("non-positive dimension"));
        }
        let n_pixels64 = (w as i64) * (h as i64);
        let n_pixels = n_pixels64 as isize;
        if n_pixels64 != (n_pixels as i64) {
            return Err(new_unsupported_error("dimension overflow"));
        }
        // There can be up to 8 bytes per pixel, for 16 bits per channel RGBA.
        if n_pixels.overflowing_mul(8).1 {
            return Err(new_unsupported_error("dimension overflow"));
        }

        self.depth = tmp[8];
        self.cb = decode_cb(self.depth, tmp[9])?;
        self.width = w as usize;
        self.height = h as usize;
        verify_checksum(r, &self.crc)
    }

    fn parse_plte<Input: std::io::BufRead>(
        &mut self,
        r: &mut Input,
        length: u32,
    ) -> std::io::Result<()> {
        let np = (length / 3) as usize; // The number of palette entries.

        if length % 3 != 0 || np == 0 || np > 256 || np > (1 << (self.depth)) {
            return Err(new_format_error("bad PLTE length"));
        }
        let mut tmp_buf = [0; 3 * 256];
        let n = 3 * np;
        r.read_exact(&mut tmp_buf[..n])?;
        self.crc.write_all(&tmp_buf[..n])?;
        match self.cb {
            CB::P1 | CB::P2 | CB::P4 | CB::P8 => {
                self.palette_vec.reserve(256 - self.palette_vec.capacity());
                for i in 0..np {
                    let c = Color::new_rgba(
                        tmp_buf[3 * i],
                        tmp_buf[3 * i + 1],
                        tmp_buf[3 * i + 2],
                        0xff,
                    );
                    self.palette_vec.push(c);
                }
            }
            CB::TC8 | CB::TCA8 | CB::TC16 | CB::TCA16 => {
                // As per the PNG spec, a PLTE chunk is optional (and for practical purposes,
                // ignorable) for the TrueColor and TrueColorAlpha color types (section 4.1.2).
            }
            _ => {
                return Err(new_format_error("PLTE, color type mismatch"));
            }
        }
        verify_checksum(r, &self.crc)
    }

    fn parset_rns<Input: std::io::BufRead>(
        &mut self,
        r: &mut Input,
        length: u32,
    ) -> std::io::Result<()> {
        let length = length as usize;
        match self.cb {
            CB::G1 | CB::G2 | CB::G4 | CB::G8 | CB::G16 => {
                if length != 2 {
                    return Err(new_format_error("bad tRNS length"));
                }
                let mut tmp = [0; 2];
                r.read_exact(&mut tmp[0..length])?;
                self.crc.write_all(&tmp[..length])?;

                compat::copy(&mut self.transparent, &tmp[..length]);
                match self.cb {
                    CB::G1 => self.transparent[1] *= 0xff,
                    CB::G2 => self.transparent[1] *= 0x55,
                    CB::G4 => self.transparent[1] *= 0x11,
                    _ => {}
                }
                self.use_transparent = true;
            }
            CB::TC8 | CB::TC16 => {
                if length != 6 {
                    return Err(new_format_error("bad tRNS length"));
                }
                let mut tmp = [0; 6];
                r.read_exact(&mut tmp[0..length])?;
                self.crc.write_all(&tmp[..length])?;

                compat::copy(&mut self.transparent, &tmp[..length]);
                self.use_transparent = true;
            }
            CB::P1 | CB::P2 | CB::P4 | CB::P8 => {
                if length > 256 {
                    return Err(new_format_error("bad tRNS length"));
                }
                let mut tmp = [0; 256];
                r.read_exact(&mut tmp[0..length])?;
                self.crc.write_all(&tmp[..length])?;
                if self.palette_vec.len() < length {
                    // Initialize the rest of the palette to opaque black. The spec (section
                    // 11.2.3) says that "any out-of-range pixel value found in the image data
                    // is an error", but some real-world PNG files have out-of-range pixel
                    // values. We fall back to opaque black, the same as libpng 1.5.13;
                    // ImageMagick 6.5.7 returns an error.
                    self.palette_vec.resize(length, color::OPAQUE_BLACK);
                }
                #[allow(clippy::needless_range_loop)]
                for i in 0..length {
                    let c = RGBA::new_from(&self.palette_vec[i]);
                    self.palette_vec[i] = Color::new_nrgba(c.r, c.g, c.b, tmp[i]);
                }
            }
            _ => return Err(new_format_error("tRNS, color type mismatch")),
        }
        verify_checksum(r, &self.crc)
    }

    fn parse_idat<Input: std::io::BufRead>(
        &mut self,
        r: &mut Input,
        length: u32,
    ) -> std::io::Result<()> {
        let mut idat_reader = &mut IdatReader {
            idat_length: length,
            r,
            crc: &mut self.crc,
        };

        let dp = DecodeParams {
            width: self.width,
            height: self.height,
            depth: self.depth,
            cb: self.cb,
            interlace: self.interlace,
            use_transparent: self.use_transparent,
            transparent: self.transparent,
        };
        let pal = convert_palette(&self.palette_vec);

        let img = {
            let mut br = std::io::BufReader::new(&mut idat_reader);
            let mut zlib_reader = match zlib::Reader::new(&mut br) {
                Ok(reader) => reader,
                Err(err) => return Err(err.to_stdio_error()),
            };
            let img = match self.interlace {
                InterlaceType::None => {
                    let mut img = allocate_image(&dp, &pal);
                    read_image_pass(&dp, &mut zlib_reader, 0, &mut img)?;
                    img
                }
                InterlaceType::Adam7 => {
                    let mut img = allocate_image(&dp, &pal);
                    for pass in 0..7 {
                        let mut img_pass = allocate_image(&dp, &pal);
                        if read_image_pass(&dp, &mut zlib_reader, pass, &mut img_pass)? {
                            merge_pass_into(&mut img, &img_pass, pass);
                        }
                    }
                    img
                }
            };

            // Check for EOF, to verify the zlib checksum.
            let mut tmp = [0; 1];
            if let Err(err) = zlib_reader.read(&mut tmp) {
                return Err(err.to_stdio_error());
            }
            img
        };

        self.palette = if self.cb.paletted() { Some(pal) } else { None };

        if idat_reader.idat_length != 0 {
            return Err(new_format_error("too much pixel data"));
        }

        self.img = Some(Box::new(img));

        verify_checksum(r, &self.crc)
    }

    fn parse_iend<Input: std::io::BufRead>(
        &mut self,
        r: &mut Input,
        length: u32,
    ) -> std::io::Result<()> {
        if length != 0 {
            return Err(new_format_error("bad IEND length"));
        }
        verify_checksum(r, &self.crc)
    }

    fn parse_chunk<Input: std::io::BufRead>(
        &mut self,
        r: &mut Input,
        config_only: bool,
    ) -> std::io::Result<()> {
        // Read the length and chunk type.
        let mut tmp = [0; 8];
        r.read_exact(&mut tmp)?;
        let length = binary::BIG_ENDIAN.uint32(&tmp[..4]);
        self.crc.reset();
        self.crc.write_all(&tmp[4..8])?;

        // Read the chunk data.
        let chunk_type = &tmp[4..8];
        match chunk_type {
            b"IHDR" => {
                if self.stage != DecodingStage::Start {
                    return Err(new_chunk_order_error());
                }
                self.stage = DecodingStage::SeenIHDR;
                return self.parse_ihdr(r, length);
            }
            b"PLTE" => {
                if self.stage != DecodingStage::SeenIHDR {
                    return Err(new_chunk_order_error());
                }
                self.stage = DecodingStage::SeenPLTE;
                return self.parse_plte(r, length);
            }
            b"tRNS" => {
                if self.cb.paletted() {
                    if self.stage != DecodingStage::SeenPLTE {
                        return Err(new_chunk_order_error());
                    }
                } else if self.cb.true_color() {
                    if self.stage != DecodingStage::SeenIHDR
                        && self.stage != DecodingStage::SeenPLTE
                    {
                        return Err(new_chunk_order_error());
                    }
                } else if self.stage != DecodingStage::SeenIHDR {
                    return Err(new_chunk_order_error());
                }
                self.stage = DecodingStage::SeentRNS;
                return self.parset_rns(r, length);
            }
            b"IDAT" => {
                if self.stage < DecodingStage::SeenIHDR
                    || self.stage > DecodingStage::SeenIDAT
                    || (self.stage == DecodingStage::SeenIHDR && self.cb.paletted())
                {
                    return Err(new_chunk_order_error());
                } else if self.stage == DecodingStage::SeenIDAT {
                    // Ignore trailing zero-length or garbage IDAT chunks.
                    //
                    // This does not affect valid PNG images that contain multiple IDAT
                    // chunks, since the first call to parseIDAT below will consume all
                    // consecutive IDAT chunks required for decoding the image.
                    // break;

                    // the chank will be consumed below
                    // return Ok(());
                } else {
                    self.stage = DecodingStage::SeenIDAT;
                    if config_only {
                        return Ok(());
                    }
                    return self.parse_idat(r, length);
                }
            }
            b"IEND" => {
                if self.stage != DecodingStage::SeenIDAT {
                    return Err(new_chunk_order_error());
                }
                self.stage = DecodingStage::SeenIEND;
                return self.parse_iend(r, length);
            }
            _ => {}
        }

        // consuming unrecognized chunk
        if length > 0x7fffffff {
            return Err(new_format_error(&format!("Bad chunk length: {}", length)));
        }
        // Ignore this chunk (of a known length).
        let mut ignored = [0_u8; 4096];
        let mut length = length as usize;
        while length > 0 {
            let size = length.min(ignored.len());
            r.read_exact(&mut ignored[..size])?;
            self.crc.write_all(&ignored[..size])?;
            length -= size;
        }
        verify_checksum(r, &self.crc)
    }
}

// merge_pass_into merges a single pass into a full sized image.
fn merge_pass_into(dst: &mut Img, src: &Img, pass: usize) {
    let bytes_per_pixel = dst.bytes_per_pixel();
    let src_pix = src.pix();
    let stride = dst.stride();
    let rect = *dst.bounds();
    let dst_pix = dst.get_pix_mutable();
    let dst_pix_len = dst_pix.len();
    let mut s = 0;
    let bounds = src.bounds();
    let p = &INTERLACING[pass];
    for y in bounds.min.y..bounds.max.y {
        let d_base = (y * p.y_factor + p.y_offset - rect.min.y) * stride as isize
            + (p.x_offset - rect.min.x) * bytes_per_pixel as isize;
        for x in bounds.min.x..bounds.max.x {
            let d = (d_base + x * p.x_factor * bytes_per_pixel as isize) as usize;
            if d <= dst_pix_len {
                compat::copy(&mut dst_pix[d..], &src_pix[s..s + bytes_per_pixel]);
            }
            s += bytes_per_pixel;
        }
    }
    if let Img::Paletted(target) = dst {
        if let Img::Paletted(source) = src {
            if target.palette.colors.len() < source.palette.colors.len() {
                // readImagePass can return a paletted image whose implicit palette
                // length (one more than the maximum Pix value) is larger than the
                // explicit palette length (what's in the PLTE chunk). Make the
                // same adjustment here.
                target
                    .palette
                    .colors
                    .resize(source.palette.colors.len(), color::OPAQUE_BLACK);
            }
        }
    }
}

fn verify_checksum<Input: std::io::BufRead>(
    r: &mut Input,
    crc: &crc32::Digest,
) -> std::io::Result<()> {
    let mut tmp = [0_u8; 4];
    r.read_exact(&mut tmp)?;

    if binary::BIG_ENDIAN.uint32(&tmp) != crc.sum32() {
        return Err(new_format_error("invalid checksum"));
    }
    Ok(())
}

fn check_header<Input: std::io::BufRead>(r: &mut Input) -> std::io::Result<()> {
    let mut tmp = [0_u8; PNG_HEADER.len()];
    r.read_exact(&mut tmp)?;
    if tmp != PNG_HEADER {
        return Err(new_format_error("not a PNG file"));
    }
    Ok(())
}

/// decode reads a PNG image from r and returns it as an image.Image.
/// The type of Image returned depends on the PNG contents.
pub fn decode<Input: std::io::BufRead>(r: &mut Input) -> std::io::Result<Box<Img>> {
    let mut d = Decoder::default();
    check_header(r)?;
    while d.stage != DecodingStage::SeenIEND {
        d.parse_chunk(r, false)?;
    }
    Ok(d.img.unwrap())
}

/// decode_config returns the color model and dimensions of a PNG image without
/// decoding the entire image.
pub fn decode_config<Input: std::io::BufRead>(r: &mut Input) -> std::io::Result<image::Config> {
    let mut d = Decoder::default();
    check_header(r)?;

    loop {
        d.parse_chunk(r, true)?;
        if d.cb.paletted() {
            if d.stage >= DecodingStage::SeentRNS {
                break;
            }
        } else if d.stage >= DecodingStage::SeenIHDR {
            break;
        }
    }

    let cm = match d.cb {
        CB::G1 | CB::G2 | CB::G4 | CB::G8 => Model::GrayModel,
        CB::GA8 => Model::NRGBAModel,
        CB::TC8 => Model::RGBAModel,
        CB::P1 | CB::P2 | CB::P4 | CB::P8 => Model::Paletted(convert_palette(&d.palette_vec)),
        CB::TCA8 => Model::NRGBAModel,
        CB::G16 => Model::Gray16Model,
        CB::GA16 => Model::NRGBA64Model,
        CB::TC16 => Model::RGBA64Model,
        CB::TCA16 => Model::NRGBA64Model,
    };
    Ok(image::Config {
        color_model: cm,
        width: d.width,
        height: d.height,
    })
}

// fn init() {
// 	image.RegisterFormat("png", PNG_HEADER, decode, decode_config)
// }

/// IdatReader presents one or more IDAT chunks as one continuous stream (minus the
/// intermediate chunk headers and footers). If the PNG data looked like:
///
/// ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2
///
/// then this reader presents xxxyy. For well-formed PNG data, the decoder state
/// immediately before the first Read call is that d.r is positioned between the
/// first IDAT and xxx, and the decoder state immediately after the last Read
/// call is that d.r is positioned between yy and crc1.
struct IdatReader<'a, Input: std::io::BufRead> {
    idat_length: u32,
    r: &'a mut Input,
    crc: &'a mut crc32::Digest<'static>,
}

impl<Input: std::io::BufRead> std::io::Read for IdatReader<'_, Input> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let mut tmp = [0_u8; 8];
        while self.idat_length == 0 {
            // We have exhausted an IDAT chunk. Verify the checksum of that chunk.
            verify_checksum(self.r, self.crc)?;
            // Read the length and chunk type of the next chunk, and check that
            // it is an IDAT chunk.
            self.r.read_exact(&mut tmp[..8])?;
            self.idat_length = binary::BIG_ENDIAN.uint32(&tmp[..4]);
            if &tmp[4..8] != b"IDAT" {
                return Err(new_format_error("not enough pixel data"));
            }
            self.crc.reset();
            self.crc.write_all(&tmp[4..8])?;
        }
        if self.idat_length >= 0x80000000 {
            return Err(new_unsupported_error("IDAT chunk length overflow"));
        }
        let bytes_to_read = buf.len().min(self.idat_length as usize);
        let n = self.r.read(&mut buf[0..bytes_to_read])?;
        self.crc.write_all(&buf[..n])?;
        self.idat_length -= n as u32;
        Ok(n)
    }
}

struct DecodeParams {
    width: usize,
    height: usize,
    depth: u8,
    cb: CB,
    interlace: InterlaceType,
    use_transparent: bool,
    transparent: [u8; 6],
}

fn convert_palette(palette: &[Color]) -> Palette {
    Palette {
        colors: palette.to_owned(),
    }
}
fn allocate_image(dp: &DecodeParams, palette: &Palette) -> Img {
    let r = image::rect(0, 0, dp.width as isize, dp.height as isize);

    match dp.cb {
        CB::G1 | CB::G2 | CB::G4 | CB::G8 => {
            if dp.use_transparent {
                Img::new_nrgba(&r)
            } else {
                Img::Gray(image::Gray::new(&r))
            }
        }
        CB::GA8 => Img::new_nrgba(&r),
        CB::TC8 => {
            if dp.use_transparent {
                Img::new_nrgba(&r)
            } else {
                Img::new_rgba(&r)
            }
        }
        CB::P1 | CB::P2 | CB::P4 | CB::P8 => {
            Img::Paletted(image::Paletted::new(&r, palette.clone()))
        }
        CB::TCA8 => Img::new_nrgba(&r),
        CB::G16 => {
            if dp.use_transparent {
                Img::new_nrgba64(&r)
            } else {
                Img::Gray16(image::Gray16::new(&r))
            }
        }
        CB::GA16 => Img::new_nrgba64(&r),
        CB::TC16 => {
            if dp.use_transparent {
                Img::new_nrgba64(&r)
            } else {
                Img::new_rgba64(&r)
            }
        }
        CB::TCA16 => Img::new_nrgba64(&r),
    }
}

/// read_image_pass reads a single image pass, sized according to the pass number.
fn read_image_pass<Input: std::io::BufRead>(
    dp: &DecodeParams,
    r: &mut zlib::Reader<Input>,
    pass: usize,
    img: &mut Img,
) -> std::io::Result<bool> {
    let mut pix_offset = 0;
    let mut width = dp.width;
    let mut height = dp.height;

    if dp.interlace == InterlaceType::Adam7 {
        let p = &INTERLACING[pass];
        // Add the multiplication factor and subtract one, effectively rounding up.
        width = ((width as isize + p.x_factor - p.x_offset - 1) / p.x_factor) as usize;
        height = ((height as isize + p.y_factor - p.y_offset - 1) / p.y_factor) as usize;
        // A PNG image can't have zero width or height, but for an interlaced
        // image, an individual pass might have zero width or height. If so, we
        // shouldn't even read a per-row filter type byte, so return early.
        if width == 0 || height == 0 {
            return Ok(false);
        }
    }

    // let mut img/* : Box<dyn image::Image>*/ =
    let bits_per_pixel: usize = match dp.cb {
        CB::G1 | CB::G2 | CB::G4 | CB::G8 => dp.depth as usize,
        CB::GA8 => 16,
        CB::TC8 => 24,
        CB::P1 | CB::P2 | CB::P4 | CB::P8 => dp.depth as usize,
        CB::TCA8 => 32,
        CB::G16 => 16,
        CB::GA16 => 32,
        CB::TC16 => 48,
        CB::TCA16 => 64,
    };
    let bytes_per_pixel = (bits_per_pixel + 7) / 8;

    // The +1 is for the per-row filter type, which is at cr[0].
    let row_size = 1 + ((bits_per_pixel as i64) * (width as i64) + 7) / 8;
    if row_size != (row_size as isize) as i64 {
        return Err(new_unsupported_error("dimension overflow"));
    }
    // cr and pr are the bytes for the current and previous row.
    let mut cr = vec![0_u8; row_size as usize];
    let mut pr = vec![0_u8; row_size as usize];

    let img_stride = img.stride();

    for y in 0..height {
        // Read the decompressed bytes.
        // 		_, err := io.ReadFull(r, cr)
        // 		if err != nil {
        // 			if err == io.EOF || err == io.ErrUnexpectedEOF {
        // 				return nil, FormatError("not enough pixel data")
        // 			}
        // 			return nil, err
        // 		}
        r.read_exact(&mut cr)?;

        // Apply the filter.
        let filter_type = cr[0];
        let cdat = &mut cr[1..];
        let pdat = &pr[1..];
        match filter_type {
            FT_NONE => {
                // No-op.
            }
            FT_SUB => {
                for i in bytes_per_pixel..cdat.len() {
                    cdat[i] = cdat[i].wrapping_add(cdat[i - bytes_per_pixel]);
                }
            }
            FT_UP => {
                for i in 0..pdat.len() {
                    cdat[i] = cdat[i].wrapping_add(pdat[i]);
                }
            }
            FT_AVERAGE => {
                // The first column has no column to the left of it, so it is a
                // special case. We know that the first column exists because we
                // check above that width != 0, and so len(cdat) != 0.
                for i in 0..bytes_per_pixel {
                    cdat[i] = cdat[i].wrapping_add(pdat[i] / 2);
                }
                for i in bytes_per_pixel..cdat.len() {
                    cdat[i] = cdat[i].wrapping_add(
                        (((cdat[i - bytes_per_pixel]) as isize + pdat[i] as isize) / 2) as u8,
                    );
                }
            }
            FT_PAETH => {
                filter_paeth(cdat, pdat, bytes_per_pixel);
            }
            _ => {
                return Err(new_format_error(&format!(
                    "bad filter type {}",
                    filter_type
                )))
            }
        }

        // Convert from bytes to colors.
        match img {
            Img::Paletted(img) => {
                read_line_to_paletted_image(dp, width, cdat, img, y, &mut pix_offset);
            }
            _ => {
                let img: &mut dyn Image = img;
                match dp.cb {
                    CB::G1 => {
                        if dp.use_transparent {
                            let ty = dp.transparent[1];
                            for x in (0..width).step_by(8) {
                                let mut b = cdat[x / 8];
                                let mut x2 = 0;
                                while x2 < 8 && x + x2 < width {
                                    let ycol = (b >> 7) * 0xff;
                                    let mut acol = 0xff_u8;
                                    if ycol == ty {
                                        acol = 0x00
                                    }
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::new_nrgba(ycol, ycol, ycol, acol),
                                    );
                                    b <<= 1;
                                    x2 += 1;
                                }
                            }
                        } else {
                            let mut x = 0;
                            while x < width {
                                let mut b = cdat[x / 8];
                                let mut x2 = 0;
                                while x2 < 8 && x + x2 < width {
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::Gray(Gray::new((b >> 7) * 0xff)),
                                    );
                                    b <<= 1;
                                    x2 += 1;
                                }
                                x += 8;
                            }
                        }
                    }
                    CB::G2 => {
                        if dp.use_transparent {
                            let ty = dp.transparent[1];
                            for x in (0..width).step_by(4) {
                                let mut b = cdat[x / 4];
                                let mut x2 = 0;
                                while x2 < 4 && x + x2 < width {
                                    let ycol = (b >> 6) * 0x55;
                                    let mut acol = 0xff_u8;
                                    if ycol == ty {
                                        acol = 0x00
                                    }
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::new_nrgba(ycol, ycol, ycol, acol),
                                    );
                                    b <<= 2;
                                    x2 += 1;
                                }
                            }
                        } else {
                            let mut x = 0;
                            while x < width {
                                let mut b = cdat[x / 4];
                                let mut x2 = 0;
                                while x2 < 4 && x + x2 < width {
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::Gray(Gray::new((b >> 6) * 0x55)),
                                    );
                                    b <<= 2;
                                    x2 += 1;
                                }
                                x += 4;
                            }
                        }
                    }
                    CB::G4 => {
                        if dp.use_transparent {
                            let ty = dp.transparent[1];
                            for x in (0..width).step_by(2) {
                                let mut b = cdat[x / 2];
                                let mut x2 = 0;
                                while x2 < 2 && x + x2 < width {
                                    let ycol = (b >> 4) * 0x11;
                                    let mut acol = 0xff_u8;
                                    if ycol == ty {
                                        acol = 0x00;
                                    }
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::new_nrgba(ycol, ycol, ycol, acol),
                                    );
                                    b <<= 4;
                                    x2 += 1;
                                }
                            }
                        } else {
                            for x in (0..width).step_by(2) {
                                let mut b = cdat[x / 2];
                                let mut x2 = 0;
                                while x2 < 2 && x + x2 < width {
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::new_gray((b >> 4) * 0x11),
                                    );
                                    b <<= 4;
                                    x2 += 1;
                                }
                            }
                            let mut x = 0;
                            while x < width {
                                let mut b = cdat[x / 2];
                                let mut x2 = 0;
                                while x2 < 2 && x + x2 < width {
                                    img.set(
                                        (x + x2) as isize,
                                        y as isize,
                                        &Color::Gray(Gray::new((b >> 4) * 0x11)),
                                    );
                                    b <<= 4;
                                    x2 += 1;
                                }
                                x += 2;
                            }
                        }
                    }
                    CB::G8 => {
                        if dp.use_transparent {
                            let ty = dp.transparent[1];
                            #[allow(clippy::needless_range_loop)]
                            for x in 0..width {
                                let ycol = cdat[x];
                                let mut acol = 0xff_u8;
                                if ycol == ty {
                                    acol = 0x00;
                                }
                                img.set(
                                    x as isize,
                                    y as isize,
                                    &Color::new_nrgba(ycol, ycol, ycol, acol),
                                );
                            }
                        } else {
                            let pix_mutable = img.get_pix_mutable();
                            compat::copy(&mut pix_mutable[pix_offset..], cdat);
                            pix_offset += img_stride;
                        }
                    }
                    CB::GA8 => {
                        for x in 0..width {
                            let ycol = cdat[2 * x];
                            img.set(
                                x as isize,
                                y as isize,
                                &Color::new_nrgba(ycol, ycol, ycol, cdat[2 * x + 1]),
                            );
                        }
                    }
                    CB::TC8 => {
                        if dp.use_transparent {
                            let pix_mutable = img.get_pix_mutable();
                            let (mut i, mut j) = (pix_offset, 0);
                            let (tr, tg, tb) =
                                (dp.transparent[1], dp.transparent[3], dp.transparent[5]);
                            for _x in 0..width {
                                let r = cdat[j];
                                let g = cdat[j + 1];
                                let b = cdat[j + 2];
                                let mut a = 0xff_u8;
                                if r == tr && g == tg && b == tb {
                                    a = 0x00;
                                }
                                pix_mutable[i] = r;
                                pix_mutable[i + 1] = g;
                                pix_mutable[i + 2] = b;
                                pix_mutable[i + 3] = a;
                                i += 4;
                                j += 3;
                            }
                            pix_offset += img_stride;
                        } else {
                            let pix_mutable = img.get_pix_mutable();
                            let (mut i, mut j) = (pix_offset, 0);
                            for _x in 0..width {
                                pix_mutable[i] = cdat[j];
                                pix_mutable[i + 1] = cdat[j + 1];
                                pix_mutable[i + 2] = cdat[j + 2];
                                pix_mutable[i + 3] = 0xff;
                                i += 4;
                                j += 3;
                            }
                            pix_offset += img_stride;
                        }
                    }
                    CB::TCA8 => {
                        let pix_mutable = img.get_pix_mutable();
                        compat::copy(&mut pix_mutable[pix_offset..], cdat);
                        pix_offset += img_stride;
                    }
                    CB::G16 => {
                        if dp.use_transparent {
                            let ty = ((dp.transparent[0] as u16) << 8) | (dp.transparent[1] as u16);
                            for x in 0..width {
                                let ycol = ((cdat[2 * x] as u16) << 8) | (cdat[2 * x + 1] as u16);
                                let acol = if ycol == ty { 0x0000 } else { 0xffff };
                                img.set(
                                    x as isize,
                                    y as isize,
                                    &Color::new_nrgba64(ycol, ycol, ycol, acol),
                                );
                            }
                        } else {
                            for x in 0..width {
                                let ycol = ((cdat[2 * x] as u16) << 8) | (cdat[2 * x + 1] as u16);
                                img.set(x as isize, y as isize, &Color::Gray16(Gray16::new(ycol)));
                            }
                        }
                    }
                    CB::GA16 => {
                        for x in 0..width {
                            let ycol = ((cdat[4 * x] as u16) << 8) | (cdat[4 * x + 1] as u16);
                            let acol = ((cdat[4 * x + 2] as u16) << 8) | (cdat[4 * x + 3] as u16);
                            img.set(
                                x as isize,
                                y as isize,
                                &Color::new_nrgba64(ycol, ycol, ycol, acol),
                            );
                        }
                    }
                    CB::TC16 => {
                        if dp.use_transparent {
                            let tr = ((dp.transparent[0] as u16) << 8) | (dp.transparent[1] as u16);
                            let tg = ((dp.transparent[2] as u16) << 8) | (dp.transparent[3] as u16);
                            let tb = ((dp.transparent[4] as u16) << 8) | (dp.transparent[5] as u16);
                            for x in 0..width {
                                let r = ((cdat[6 * x] as u16) << 8) | (cdat[6 * x + 1] as u16);
                                let g = ((cdat[6 * x + 2] as u16) << 8) | (cdat[6 * x + 3] as u16);
                                let b = ((cdat[6 * x + 4] as u16) << 8) | (cdat[6 * x + 5] as u16);
                                let a = if r == tr && g == tg && b == tb {
                                    0x0000
                                } else {
                                    0xffff
                                };
                                img.set(x as isize, y as isize, &Color::new_nrgba64(r, g, b, a));
                            }
                        } else {
                            for x in 0..width {
                                let r = ((cdat[6 * x] as u16) << 8) | (cdat[6 * x + 1] as u16);
                                let g = ((cdat[6 * x + 2] as u16) << 8) | (cdat[6 * x + 3] as u16);
                                let b = ((cdat[6 * x + 4] as u16) << 8) | (cdat[6 * x + 5] as u16);
                                img.set(
                                    x as isize,
                                    y as isize,
                                    &Color::new_rgba64(r, g, b, 0xffff),
                                );
                            }
                        }
                    }
                    CB::TCA16 => {
                        for x in 0..width {
                            let r = ((cdat[8 * x] as u16) << 8) | (cdat[8 * x + 1] as u16);
                            let g = ((cdat[8 * x + 2] as u16) << 8) | (cdat[8 * x + 3] as u16);
                            let b = ((cdat[8 * x + 4] as u16) << 8) | (cdat[8 * x + 5] as u16);
                            let a = ((cdat[8 * x + 6] as u16) << 8) | (cdat[8 * x + 7] as u16);
                            img.set(x as isize, y as isize, &Color::new_nrgba64(r, g, b, a));
                        }
                    }
                    _ => panic!("unreachable"),
                }
            }
        }

        // The current row for y is the previous row for y+1.
        std::mem::swap(&mut pr, &mut cr);
    }
    Ok(true)
}

fn read_line_to_paletted_image(
    dp: &DecodeParams,
    width: usize,
    cdat: &mut [u8],
    img: &mut image::Paletted,
    y: usize,
    pix_offset: &mut usize,
) {
    match dp.cb {
        CB::P1 => {
            for x in (0..width).step_by(8) {
                let mut b = cdat[x / 8];
                let mut x2 = 0;
                while x2 < 8 && x + x2 < width {
                    let idx = (b >> 7) as usize;
                    if img.palette.colors.len() <= idx {
                        img.palette.colors.resize(idx + 1, color::OPAQUE_BLACK);
                    }
                    img.set_color_index((x + x2) as isize, y as isize, idx as u8);
                    b <<= 1;
                    x2 += 1;
                }
            }
        }
        CB::P2 => {
            for x in (0..width).step_by(4) {
                let mut b = cdat[x / 4];
                let mut x2 = 0;
                while x2 < 4 && x + x2 < width {
                    let idx = (b >> 6) as usize;
                    if img.palette.colors.len() <= idx {
                        img.palette.colors.resize(idx + 1, color::OPAQUE_BLACK);
                    }
                    img.set_color_index((x + x2) as isize, y as isize, idx as u8);
                    b <<= 2;
                    x2 += 1;
                }
            }
        }
        CB::P4 => {
            for x in (0..width).step_by(2) {
                let mut b = cdat[x / 2];
                let mut x2 = 0;
                while x2 < 2 && x + x2 < width {
                    let idx = (b >> 4) as usize;
                    if img.palette.colors.len() <= idx {
                        img.palette.colors.resize(idx + 1, color::OPAQUE_BLACK);
                    }
                    img.set_color_index((x + x2) as isize, y as isize, idx as u8);
                    b <<= 4;
                    x2 += 1;
                }
            }
        }
        CB::P8 => {
            if img.palette.colors.len() != 256 {
                #[allow(clippy::needless_range_loop)]
                for x in 0..width {
                    if img.palette.colors.len() <= cdat[x] as usize {
                        img.palette
                            .colors
                            .resize((cdat[x] as usize) + 1, color::OPAQUE_BLACK);
                    }
                }
            }
            compat::copy(&mut img.get_pix_mutable()[*pix_offset..], cdat);
            *pix_offset += img.stride();
        }
        _ => panic!("unreachable"),
    }
}