jxl_bitstream/
error.rs

1/// The error type for JPEG XL bitstream-level operations.
2///
3/// Other crates of jxl-oxide may return `ValidationFailed` or `ProfileConformance` errors while
4/// validating decoded data.
5#[derive(Debug)]
6#[non_exhaustive]
7pub enum Error {
8    Io(std::io::Error),
9    /// Container was invalid.
10    InvalidBox,
11    /// `PadZeroToByte` read non-zero bits.
12    NonZeroPadding,
13    /// Parsed floating point value was Infinity or NaN.
14    InvalidFloat,
15    /// Parsed value couldn't be represented with the given enum.
16    InvalidEnum {
17        name: &'static str,
18        value: u32,
19    },
20    /// The bitstream is invalid.
21    ValidationFailed(&'static str),
22    /// The codestream does not conform to the current decoder profile.
23    ProfileConformance(&'static str),
24    /// The bitstream couldn't be skipped to the given position, mainly due to the direction being
25    /// backwards.
26    CannotSkip,
27    /// The bistream offsed was not aligned to read byte-aligned data.
28    NotAligned,
29}
30
31impl std::error::Error for Error {
32    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
33        match self {
34            Self::Io(e) => Some(e),
35            _ => None,
36        }
37    }
38}
39
40impl std::fmt::Display for Error {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::Io(e) => {
44                write!(f, "I/O error: {e}")
45            }
46            Self::InvalidBox => write!(f, "invalid container"),
47            Self::NonZeroPadding => {
48                write!(f, "PadZeroToByte() read non-zero bits")
49            }
50            Self::InvalidFloat => {
51                write!(f, "F16() read NaN or Infinity")
52            }
53            Self::InvalidEnum { name, value } => {
54                write!(f, "Enum({name}) read invalid enum value of {value}")
55            }
56            Self::ValidationFailed(msg) => {
57                write!(f, "bitstream validation failed: {msg}")
58            }
59            Self::ProfileConformance(msg) => {
60                write!(f, "not supported by current profile: {msg}")
61            }
62            Self::CannotSkip => {
63                write!(f, "target bookmark already passed")
64            }
65            Self::NotAligned => {
66                write!(f, "bitstream is unaligned")
67            }
68        }
69    }
70}
71
72impl From<std::io::Error> for Error {
73    fn from(e: std::io::Error) -> Self {
74        Self::Io(e)
75    }
76}
77
78impl Error {
79    pub fn unexpected_eof(&self) -> bool {
80        if let Error::Io(e) = self {
81            return e.kind() == std::io::ErrorKind::UnexpectedEof;
82        }
83        false
84    }
85}
86
87/// Shorthand for result type of `jxl_bitstream`.
88pub type BitstreamResult<T> = std::result::Result<T, Error>;