1use core::convert::Infallible;
2use core::fmt::{self, Display};
3
4use crate::consts::QOI_MAGIC;
5
6#[derive(Debug)]
8pub enum Error {
9 InvalidMagic { magic: u32 },
11 InvalidChannels { channels: u8 },
13 InvalidColorSpace { colorspace: u8 },
15 InvalidImageDimensions { width: u32, height: u32 },
17 InvalidImageLength { size: usize, width: u32, height: u32 },
19 OutputBufferTooSmall { size: usize, required: usize },
21 UnexpectedBufferEnd,
23 InvalidPadding,
25 InvalidStride { stride: usize },
27 #[cfg(feature = "std")]
28 IoError(std::io::Error),
30}
31
32pub type Result<T> = core::result::Result<T, Error>;
34
35impl Display for Error {
36 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 match *self {
38 Self::InvalidMagic { magic } => {
39 write!(f, "invalid magic: expected {:?}, got {:?}", QOI_MAGIC, magic.to_be_bytes())
40 }
41 Self::InvalidChannels { channels } => {
42 write!(f, "invalid number of channels: {channels}")
43 }
44 Self::InvalidColorSpace { colorspace } => {
45 write!(f, "invalid color space: {colorspace} (expected 0 or 1)")
46 }
47 Self::InvalidImageDimensions { width, height } => {
48 write!(f, "invalid image dimensions: {width}x{height}")
49 }
50 Self::InvalidImageLength { size, width, height } => {
51 write!(f, "invalid image length: {size} bytes for {width}x{height}")
52 }
53 Self::OutputBufferTooSmall { size, required } => {
54 write!(f, "output buffer size too small: {size} (required: {required})")
55 }
56 Self::UnexpectedBufferEnd => {
57 write!(f, "unexpected input buffer end while decoding")
58 }
59 Self::InvalidPadding => {
60 write!(f, "invalid padding (stream end marker mismatch)")
61 }
62 Self::InvalidStride { stride } => {
63 write!(f, "invalid stride: {stride}")
64 }
65 #[cfg(feature = "std")]
66 Self::IoError(ref err) => {
67 write!(f, "i/o error: {err}")
68 }
69 }
70 }
71}
72
73#[cfg(feature = "std")]
74impl std::error::Error for Error {}
75
76impl From<Infallible> for Error {
77 fn from(_: Infallible) -> Self {
78 unreachable!()
79 }
80}
81
82#[cfg(feature = "std")]
83impl From<std::io::Error> for Error {
84 fn from(err: std::io::Error) -> Self {
85 Self::IoError(err)
86 }
87}