1use 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#[derive(Clone, Debug, PartialEq)]
14pub enum EncodeError {
15 InvalidDimensions {
17 width: u32,
19 height: u32,
21 },
22 UnsupportedFormat {
24 color: ColorType,
26 bit_depth: BitDepth,
28 },
29 DataLengthMismatch {
31 expected: usize,
33 actual: usize,
35 },
36 ImageTooLarge,
38 InvalidTextKeyword(String),
41 InvalidTextValue {
43 keyword: String,
45 },
46 InvalidDpi(f64),
49 NoFrames,
51 FrameMismatch {
53 index: usize,
55 },
56 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#[derive(Clone, Debug, PartialEq, Eq)]
111pub enum DecodeError {
112 InvalidSignature,
114 UnexpectedEof,
116 ChunkTooLong {
118 length: u32,
120 },
121 InvalidChunkType(ChunkType),
123 CrcMismatch {
125 chunk: ChunkType,
127 stored: u32,
129 computed: u32,
131 },
132 MissingHeader,
134 InvalidChunkLength {
136 chunk: ChunkType,
138 length: usize,
140 },
141 InvalidDimensions {
143 width: u32,
145 height: u32,
147 },
148 InvalidFormat {
150 color_type: u8,
152 bit_depth: u8,
154 },
155 UnsupportedCompressionMethod(u8),
157 UnsupportedFilterMethod(u8),
159 UnsupportedInterlaceMethod(u8),
161 DuplicateChunk(ChunkType),
163 ChunkOutOfOrder(ChunkType),
166 UnknownCriticalChunk(ChunkType),
168 MissingPalette,
170 InvalidPalette {
173 length: usize,
175 },
176 UnexpectedPalette,
178 InvalidTransparency,
181 MissingImageData,
183 ImageTooLarge {
185 limit: usize,
187 },
188 Zlib(ZlibError),
190 ImageDataTooShort {
192 expected: usize,
194 actual: usize,
196 },
197 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}