Skip to main content

pltrs_codec/png/
chunk.rs

1//! PNG chunk framing: length, type, data and CRC.
2
3use std::fmt;
4
5use super::error::DecodeError;
6use crate::checksum::Crc32;
7
8/// The eight bytes every PNG file starts with.
9pub const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1A, b'\n'];
10
11/// Largest chunk length PNG allows (2^31 − 1).
12pub(crate) const MAX_CHUNK_LEN: u32 = (1 << 31) - 1;
13
14/// A four-letter chunk type such as `IHDR`.
15#[derive(Clone, Copy, PartialEq, Eq, Hash)]
16pub struct ChunkType(pub [u8; 4]);
17
18impl ChunkType {
19    /// Image header.
20    pub const IHDR: Self = Self(*b"IHDR");
21    /// Palette.
22    pub const PLTE: Self = Self(*b"PLTE");
23    /// Image data.
24    pub const IDAT: Self = Self(*b"IDAT");
25    /// Image end.
26    pub const IEND: Self = Self(*b"IEND");
27    /// Simple transparency.
28    pub const TRNS: Self = Self(*b"tRNS");
29    /// Physical pixel dimensions.
30    pub const PHYS: Self = Self(*b"pHYs");
31    /// Latin-1 text.
32    pub const TEXT: Self = Self(*b"tEXt");
33    /// Compressed Latin-1 text.
34    pub const ZTXT: Self = Self(*b"zTXt");
35    /// International (UTF-8) text.
36    pub const ITXT: Self = Self(*b"iTXt");
37
38    /// Whether decoders must understand this chunk (upper-case first letter).
39    pub const fn is_critical(self) -> bool {
40        self.0[0].is_ascii_uppercase()
41    }
42
43    /// Whether every byte is an ASCII letter, as PNG requires.
44    const fn is_valid(self) -> bool {
45        let [a, b, c, d] = self.0;
46        a.is_ascii_alphabetic()
47            && b.is_ascii_alphabetic()
48            && c.is_ascii_alphabetic()
49            && d.is_ascii_alphabetic()
50    }
51}
52
53impl fmt::Display for ChunkType {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        for &byte in &self.0 {
56            write!(f, "{}", std::ascii::escape_default(byte))?;
57        }
58        Ok(())
59    }
60}
61
62impl fmt::Debug for ChunkType {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "ChunkType({self})")
65    }
66}
67
68/// Appends a complete chunk to `out`.
69pub(crate) fn write_chunk(out: &mut Vec<u8>, kind: ChunkType, data: &[u8]) {
70    let length = u32::try_from(data.len())
71        .ok()
72        .filter(|&len| len <= MAX_CHUNK_LEN)
73        .expect("encoder chunks are split well below the PNG size limit");
74    out.extend_from_slice(&length.to_be_bytes());
75    out.extend_from_slice(&kind.0);
76    out.extend_from_slice(data);
77    let mut crc = Crc32::new();
78    crc.update(&kind.0);
79    crc.update(data);
80    out.extend_from_slice(&crc.finish().to_be_bytes());
81}
82
83/// A chunk read from a PNG stream, with its CRC already verified.
84#[derive(Clone, Copy, Debug)]
85pub(crate) struct Chunk<'a> {
86    pub(crate) kind: ChunkType,
87    pub(crate) data: &'a [u8],
88}
89
90/// Splits the bytes after the signature into chunks.
91#[derive(Debug)]
92pub(crate) struct ChunkReader<'a> {
93    rest: &'a [u8],
94}
95
96impl<'a> ChunkReader<'a> {
97    /// Checks the signature and positions the reader on the first chunk.
98    pub(crate) fn new(png: &'a [u8]) -> Result<Self, DecodeError> {
99        let rest = png
100            .strip_prefix(&SIGNATURE)
101            .ok_or(DecodeError::InvalidSignature)?;
102        Ok(Self { rest })
103    }
104
105    /// Reads the next chunk; running out of data is an error because a valid
106    /// stream ends with `IEND`, after which nothing more is read.
107    pub(crate) fn next_chunk(&mut self) -> Result<Chunk<'a>, DecodeError> {
108        let (&header, rest) = self
109            .rest
110            .split_first_chunk::<8>()
111            .ok_or(DecodeError::UnexpectedEof)?;
112        let [l0, l1, l2, l3, t0, t1, t2, t3] = header;
113        let length = u32::from_be_bytes([l0, l1, l2, l3]);
114        let kind = ChunkType([t0, t1, t2, t3]);
115        if length > MAX_CHUNK_LEN {
116            return Err(DecodeError::ChunkTooLong { length });
117        }
118        if !kind.is_valid() {
119            return Err(DecodeError::InvalidChunkType(kind));
120        }
121        let length = length as usize;
122        if rest.len() < length + 4 {
123            return Err(DecodeError::UnexpectedEof);
124        }
125        let (data, rest) = rest.split_at(length);
126        let (crc_bytes, rest) = rest.split_at(4);
127        let stored = u32::from_be_bytes([crc_bytes[0], crc_bytes[1], crc_bytes[2], crc_bytes[3]]);
128        let mut crc = Crc32::new();
129        crc.update(&kind.0);
130        crc.update(data);
131        let computed = crc.finish();
132        if stored != computed {
133            return Err(DecodeError::CrcMismatch {
134                chunk: kind,
135                stored,
136                computed,
137            });
138        }
139        self.rest = rest;
140        Ok(Chunk { kind, data })
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn writes_iend_like_every_png() {
150        let mut out = Vec::new();
151        write_chunk(&mut out, ChunkType::IEND, &[]);
152        assert_eq!(
153            out,
154            [0, 0, 0, 0, b'I', b'E', b'N', b'D', 0xAE, 0x42, 0x60, 0x82]
155        );
156    }
157
158    #[test]
159    fn reads_back_written_chunks() {
160        let mut png = SIGNATURE.to_vec();
161        write_chunk(&mut png, ChunkType::TEXT, b"Title\0plot");
162        write_chunk(&mut png, ChunkType::IEND, &[]);
163        let mut reader = ChunkReader::new(&png).unwrap();
164        let text = reader.next_chunk().unwrap();
165        assert_eq!(
166            (text.kind, text.data),
167            (ChunkType::TEXT, &b"Title\0plot"[..])
168        );
169        assert!(!text.kind.is_critical());
170        assert_eq!(reader.next_chunk().unwrap().kind, ChunkType::IEND);
171        assert_eq!(reader.next_chunk().unwrap_err(), DecodeError::UnexpectedEof);
172    }
173
174    #[test]
175    fn rejects_damaged_framing() {
176        assert_eq!(
177            ChunkReader::new(b"\x89PNG").unwrap_err(),
178            DecodeError::InvalidSignature
179        );
180        let mut png = SIGNATURE.to_vec();
181        write_chunk(&mut png, ChunkType::IEND, &[]);
182
183        let mut bad_crc = png.clone();
184        *bad_crc.last_mut().unwrap() ^= 1;
185        assert!(matches!(
186            ChunkReader::new(&bad_crc).unwrap().next_chunk(),
187            Err(DecodeError::CrcMismatch {
188                chunk: ChunkType::IEND,
189                ..
190            })
191        ));
192
193        let mut bad_type = png.clone();
194        bad_type[12] = b'1';
195        assert_eq!(
196            ChunkReader::new(&bad_type)
197                .unwrap()
198                .next_chunk()
199                .unwrap_err(),
200            DecodeError::InvalidChunkType(ChunkType(*b"1END"))
201        );
202
203        let mut too_long = png.clone();
204        too_long[8] = 0x80;
205        assert_eq!(
206            ChunkReader::new(&too_long)
207                .unwrap()
208                .next_chunk()
209                .unwrap_err(),
210            DecodeError::ChunkTooLong {
211                length: 0x8000_0000
212            }
213        );
214
215        let truncated = &png[..png.len() - 1];
216        assert_eq!(
217            ChunkReader::new(truncated)
218                .unwrap()
219                .next_chunk()
220                .unwrap_err(),
221            DecodeError::UnexpectedEof
222        );
223    }
224
225    #[test]
226    fn displays_chunk_types_safely() {
227        assert_eq!(ChunkType::PHYS.to_string(), "pHYs");
228        assert_eq!(ChunkType([b'a', 0, 0xFF, b'Z']).to_string(), "a\\x00\\xffZ");
229        assert_eq!(format!("{:?}", ChunkType::IDAT), "ChunkType(IDAT)");
230    }
231}