Skip to main content

pltrs_codec/png/
error.rs

1//! PNG encoding and decoding errors.
2
3use std::error::Error;
4use std::fmt;
5
6use pltrs_core::alloc::OutOfMemory;
7
8use super::chunk::ChunkType;
9use super::types::{BitDepth, ColorType};
10use crate::zlib::ZlibError;
11
12/// An error preventing an image from being encoded.
13#[derive(Clone, Debug, PartialEq)]
14pub enum EncodeError {
15    /// Width or height is zero or above 2^31 − 1.
16    InvalidDimensions {
17        /// The requested width.
18        width: u32,
19        /// The requested height.
20        height: u32,
21    },
22    /// The encoder does not write this colour type / bit depth combination.
23    UnsupportedFormat {
24        /// The requested colour type.
25        color: ColorType,
26        /// The requested bit depth.
27        bit_depth: BitDepth,
28    },
29    /// The pixel data does not have the size the dimensions imply.
30    DataLengthMismatch {
31        /// Bytes the dimensions and format require.
32        expected: usize,
33        /// Bytes supplied.
34        actual: usize,
35    },
36    /// The image is too large to address in memory.
37    ImageTooLarge,
38    /// A text keyword is empty, longer than 79 bytes, not printable Latin-1,
39    /// or has leading, trailing or consecutive spaces.
40    InvalidTextKeyword(String),
41    /// A text value contains a NUL character or does not fit in a chunk.
42    InvalidTextValue {
43        /// The keyword of the offending entry.
44        keyword: String,
45    },
46    /// A resolution is not a finite positive number of dots per inch that
47    /// fits the `pHYs` chunk.
48    InvalidDpi(f64),
49    /// An animated PNG needs at least one frame.
50    NoFrames,
51    /// An animation frame differs in size or format from the first one.
52    FrameMismatch {
53        /// The offending frame.
54        index: usize,
55    },
56    /// The memory for the encoded image cannot be allocated.
57    OutOfMemory(OutOfMemory),
58}
59
60impl fmt::Display for EncodeError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::InvalidDimensions { width, height } => {
64                write!(f, "invalid PNG dimensions {width}×{height}")
65            }
66            Self::UnsupportedFormat { color, bit_depth } => {
67                write!(f, "cannot encode {bit_depth} {color} PNG images")
68            }
69            Self::DataLengthMismatch { expected, actual } => write!(
70                f,
71                "pixel data has {actual} bytes but the image needs {expected}"
72            ),
73            Self::ImageTooLarge => f.write_str("image is too large to encode"),
74            Self::InvalidTextKeyword(keyword) => {
75                write!(f, "invalid PNG text keyword {keyword:?}")
76            }
77            Self::InvalidTextValue { keyword } => {
78                write!(
79                    f,
80                    "invalid PNG text for keyword {keyword:?}: NUL character or too long"
81                )
82            }
83            Self::InvalidDpi(dpi) => write!(f, "invalid resolution of {dpi} dpi"),
84            Self::NoFrames => f.write_str("an animated PNG needs at least one frame"),
85            Self::FrameMismatch { index } => write!(
86                f,
87                "animation frame {index} differs in size or format from the first"
88            ),
89            Self::OutOfMemory(err) => write!(f, "cannot encode the image: {err}"),
90        }
91    }
92}
93
94impl Error for EncodeError {
95    fn source(&self) -> Option<&(dyn Error + 'static)> {
96        match self {
97            Self::OutOfMemory(err) => Some(err),
98            _ => None,
99        }
100    }
101}
102
103impl From<OutOfMemory> for EncodeError {
104    fn from(err: OutOfMemory) -> Self {
105        Self::OutOfMemory(err)
106    }
107}
108
109/// An error found while decoding a PNG file.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub enum DecodeError {
112    /// The data does not start with the PNG signature.
113    InvalidSignature,
114    /// The data ended inside a chunk or before the `IEND` chunk.
115    UnexpectedEof,
116    /// A chunk declares a length above 2^31 − 1.
117    ChunkTooLong {
118        /// The declared length.
119        length: u32,
120    },
121    /// A chunk type contains bytes other than ASCII letters.
122    InvalidChunkType(ChunkType),
123    /// A chunk's CRC does not match its contents.
124    CrcMismatch {
125        /// The damaged chunk.
126        chunk: ChunkType,
127        /// CRC stored in the file.
128        stored: u32,
129        /// CRC of the chunk as read.
130        computed: u32,
131    },
132    /// The first chunk is not `IHDR`.
133    MissingHeader,
134    /// A chunk with a fixed layout has the wrong length.
135    InvalidChunkLength {
136        /// The chunk concerned.
137        chunk: ChunkType,
138        /// Its actual length.
139        length: usize,
140    },
141    /// Width or height is zero or above 2^31 − 1.
142    InvalidDimensions {
143        /// The declared width.
144        width: u32,
145        /// The declared height.
146        height: u32,
147    },
148    /// The colour type / bit depth pair is not allowed by PNG.
149    InvalidFormat {
150        /// The `IHDR` colour type code.
151        color_type: u8,
152        /// The `IHDR` bit depth.
153        bit_depth: u8,
154    },
155    /// The compression method is not 0 (DEFLATE).
156    UnsupportedCompressionMethod(u8),
157    /// The filter method is not 0 (adaptive filtering).
158    UnsupportedFilterMethod(u8),
159    /// The interlace method is neither 0 (none) nor 1 (Adam7).
160    UnsupportedInterlaceMethod(u8),
161    /// A chunk that may occur only once occurs again.
162    DuplicateChunk(ChunkType),
163    /// A critical chunk appears where it is not allowed, e.g. `PLTE` after
164    /// `IDAT`, or `IDAT` chunks that are not consecutive.
165    ChunkOutOfOrder(ChunkType),
166    /// A critical chunk this decoder does not know.
167    UnknownCriticalChunk(ChunkType),
168    /// An indexed image has no `PLTE` chunk.
169    MissingPalette,
170    /// A palette is empty, larger than 256 entries, or not a whole number of
171    /// RGB triples.
172    InvalidPalette {
173        /// Length of the `PLTE` data.
174        length: usize,
175    },
176    /// A palette appears in a greyscale image.
177    UnexpectedPalette,
178    /// A `tRNS` chunk has the wrong size, or appears in an image with an
179    /// alpha channel.
180    InvalidTransparency,
181    /// There is no `IDAT` chunk.
182    MissingImageData,
183    /// The decoded image would exceed the decoder's size limit.
184    ImageTooLarge {
185        /// The limit, in bytes.
186        limit: usize,
187    },
188    /// The image data is not a valid zlib stream.
189    Zlib(ZlibError),
190    /// The image data decompresses to fewer bytes than the image needs.
191    ImageDataTooShort {
192        /// Bytes the image needs.
193        expected: usize,
194        /// Bytes found.
195        actual: usize,
196    },
197    /// A scanline uses a filter type other than 0–4.
198    InvalidFilterType(u8),
199}
200
201impl fmt::Display for DecodeError {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        match self {
204            Self::InvalidSignature => f.write_str("not a PNG file (bad signature)"),
205            Self::UnexpectedEof => f.write_str("PNG data ended unexpectedly"),
206            Self::ChunkTooLong { length } => write!(f, "chunk length {length} is too large"),
207            Self::InvalidChunkType(chunk) => write!(f, "invalid chunk type {chunk:?}"),
208            Self::CrcMismatch {
209                chunk,
210                stored,
211                computed,
212            } => write!(
213                f,
214                "CRC mismatch in {chunk} chunk: stored {stored:#010x}, computed {computed:#010x}"
215            ),
216            Self::MissingHeader => f.write_str("PNG does not start with an IHDR chunk"),
217            Self::InvalidChunkLength { chunk, length } => {
218                write!(f, "{chunk} chunk has invalid length {length}")
219            }
220            Self::InvalidDimensions { width, height } => {
221                write!(f, "invalid PNG dimensions {width}×{height}")
222            }
223            Self::InvalidFormat {
224                color_type,
225                bit_depth,
226            } => write!(
227                f,
228                "invalid colour type {color_type} with bit depth {bit_depth}"
229            ),
230            Self::UnsupportedCompressionMethod(method) => {
231                write!(f, "unsupported compression method {method}")
232            }
233            Self::UnsupportedFilterMethod(method) => {
234                write!(f, "unsupported filter method {method}")
235            }
236            Self::UnsupportedInterlaceMethod(method) => {
237                write!(f, "unsupported interlace method {method}")
238            }
239            Self::DuplicateChunk(chunk) => write!(f, "duplicate {chunk} chunk"),
240            Self::ChunkOutOfOrder(chunk) => write!(f, "{chunk} chunk out of order"),
241            Self::UnknownCriticalChunk(chunk) => write!(f, "unknown critical chunk {chunk}"),
242            Self::MissingPalette => f.write_str("indexed image has no palette"),
243            Self::InvalidPalette { length } => write!(f, "invalid palette of {length} bytes"),
244            Self::UnexpectedPalette => f.write_str("greyscale image has a palette"),
245            Self::InvalidTransparency => f.write_str("invalid tRNS chunk"),
246            Self::MissingImageData => f.write_str("PNG has no IDAT chunk"),
247            Self::ImageTooLarge { limit } => {
248                write!(f, "decoded image would exceed the limit of {limit} bytes")
249            }
250            Self::Zlib(error) => write!(f, "invalid image data: {error}"),
251            Self::ImageDataTooShort { expected, actual } => write!(
252                f,
253                "image data has {actual} bytes after decompression, {expected} needed"
254            ),
255            Self::InvalidFilterType(filter) => write!(f, "invalid scanline filter type {filter}"),
256        }
257    }
258}
259
260impl Error for DecodeError {
261    fn source(&self) -> Option<&(dyn Error + 'static)> {
262        match self {
263            Self::Zlib(error) => Some(error),
264            _ => None,
265        }
266    }
267}
268
269impl From<ZlibError> for DecodeError {
270    fn from(error: ZlibError) -> Self {
271        Self::Zlib(error)
272    }
273}