rust_j2k/error.rs
1//! Error type for the decoder. One flat enum; each failure maps to the variant
2//! that names its class, so a caller can tell a malformed input from an
3//! unsupported feature: [`Error::Codestream`] for structural damage,
4//! [`Error::Marker`] for an invalid field value, [`Error::FileFormat`] for a
5//! malformed JP2 box structure, [`Error::Unsupported`] for
6//! a valid-but-out-of-subset feature, [`Error::Limit`] for an input past a
7//! decoder resource guard, [`Error::InvalidOptions`] for bad caller options,
8//! and [`Error::Inconsistent`] for a violated internal invariant. Structural
9//! corruption anywhere in the pipeline — including packet headers and coded
10//! data — reports as [`Error::Codestream`].
11
12use core::fmt;
13
14/// Crate result alias.
15pub type Result<T> = core::result::Result<T, Error>;
16
17/// A decode failure, tagged by the class of fault.
18///
19/// Match on the variant to decide what to do; the `String` inside is a
20/// diagnostic for a log. Its wording can change between releases, so do not
21/// parse it or compare it. Input that is not JPEG 2000 at all, empty input
22/// and plain text included, is [`Error::Codestream`].
23///
24/// The variant also says what to tell a user:
25///
26/// | Variant | A message for a user |
27/// | ------- | -------------------- |
28/// | `Codestream`, `Marker`, `FileFormat` | The file is damaged, truncated or not a JPEG 2000 image. |
29/// | `Unsupported` | The file uses a JPEG 2000 feature this decoder does not read. |
30/// | `Limit` | The file is larger or costlier than the decoder allows by default. If the message names a `DecodeOptions` limit, it can be retried with a higher [`WorkLimit`](crate::WorkLimit). |
31/// | `InvalidOptions` | The decode options are invalid, for any file (`WorkLimit::Raised(0)`, sRGB output with `raw_channels`) or for this one (a reduction past the file's levels). |
32/// | `Inconsistent` | An internal error; please file a bug. |
33///
34/// Damage does not always show as the first row. A flipped bit in a header
35/// field can read as an absurd image size (`Limit`), an unknown marker or a
36/// feature the decoder does not read (`Unsupported`), so a corrupt file can
37/// come back as any of those. Do not retry a `Limit` with
38/// [`WorkLimit::Unlimited`](crate::WorkLimit::Unlimited) unless the source
39/// is trusted.
40///
41/// ```
42/// use rust_j2k::{Error, decode};
43///
44/// fn explain(error: &Error) -> &'static str {
45/// match error {
46/// Error::Codestream(_) | Error::Marker(_) | Error::FileFormat(_) => {
47/// "the file is damaged, truncated or not a JPEG 2000 image"
48/// }
49/// Error::Unsupported(_) => "the file uses a feature this decoder does not read",
50/// Error::Limit(_) => "the file is larger or costlier than the decoder allows",
51/// Error::InvalidOptions(_) => "the decode options do not fit this file",
52/// // The enum is `#[non_exhaustive]`: a later version can add variants.
53/// _ => "the file could not be decoded",
54/// }
55/// }
56///
57/// let error = decode(b"").unwrap_err();
58/// assert!(matches!(error, Error::Codestream(_)));
59/// assert_eq!(
60/// explain(&error),
61/// "the file is damaged, truncated or not a JPEG 2000 image"
62/// );
63/// ```
64#[derive(Debug, Clone, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum Error {
67 /// Not a JPEG 2000 codestream, or its structure is broken: a truncated or
68 /// missing segment, lost sync, or corrupt packet / coded data. Any input
69 /// that is not JPEG 2000 at all (empty input, text, another image
70 /// format) is this variant, since it has no `SOC` marker.
71 Codestream(String),
72 /// A marker segment has an invalid field: a reserved value, a bad length
73 /// or an out-of-range value.
74 Marker(String),
75 /// The JP2 box structure or a box field is malformed: a truncated box, a
76 /// missing or misplaced required box, an invalid field value, or a box
77 /// that disagrees with the codestream.
78 FileFormat(String),
79 /// A valid-but-not-decoded feature: an HTJ2K codestream, a Part 2
80 /// extension, a JP2 box this decoder cannot apply, a file that is not
81 /// JP2-compatible. A newer version of the decoder may accept the same
82 /// input.
83 Unsupported(String),
84 /// The input exceeded one of the decoder's resource guards: a hostile or
85 /// absurd declaration (code-block count, precinct count, bit-plane depth)
86 /// past a cap, an image of more samples than the sample limit allows, or
87 /// work past the bound for the file's size (see [`decode`](crate::decode)).
88 /// It is not a missing feature (that is [`Error::Unsupported`]), and the
89 /// file may be valid.
90 ///
91 /// Three of these can be changed, each with a [`WorkLimit`](crate::WorkLimit):
92 /// the sample limit
93 /// ([`DecodeOptions::sample_limit`](crate::DecodeOptions::sample_limit)),
94 /// which holds the image area and the samples that palette expansion, sYCC
95 /// chroma replication and a monochrome ICC conversion produce; reading the
96 /// packet headers
97 /// ([`DecodeOptions::packet_work_limit`](crate::DecodeOptions::packet_work_limit));
98 /// and decoding the code-blocks
99 /// ([`DecodeOptions::code_block_work_limit`](crate::DecodeOptions::code_block_work_limit)).
100 /// The message of one of them names the option and a `WorkLimit::Raised`
101 /// factor; the factor is a hint (see [`WorkLimit`](crate::WorkLimit)), not
102 /// a measure of the file.
103 ///
104 /// The other guards have no option, so a file past one of them is refused
105 /// whatever the options. A tile may hold at most 2^19 code-blocks and
106 /// 2^18 precincts, and 32 progression order change (POC) volumes; a
107 /// code-block may have at most 30 bit-planes; and under a `sample_limit`
108 /// of `WorkLimit::Unlimited`, an image too large for the target to
109 /// address is still refused. [`WorkLimit`](crate::WorkLimit) has an
110 /// example that retries.
111 Limit(String),
112 /// The caller passed [`DecodeOptions`](crate::DecodeOptions) that are
113 /// invalid for this codestream, or that are invalid whatever the input
114 /// (sRGB output with `raw_channels`, or a limit of `WorkLimit::Raised(0)`).
115 /// The input itself may be fine.
116 InvalidOptions(String),
117 /// A decoder invariant was violated (declared geometry and decoded state
118 /// disagreed where they never should); please file a bug.
119 Inconsistent(String),
120}
121
122impl fmt::Display for Error {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 match self {
125 Error::Codestream(m) => write!(f, "codestream: {m}"),
126 Error::Marker(m) => write!(f, "marker: {m}"),
127 Error::FileFormat(m) => write!(f, "file format: {m}"),
128 Error::Unsupported(m) => write!(f, "unsupported: {m}"),
129 Error::Limit(m) => write!(f, "limit: {m}"),
130 Error::InvalidOptions(m) => write!(f, "invalid options: {m}"),
131 Error::Inconsistent(m) => write!(f, "decoder bug (please report it): {m}"),
132 }
133 }
134}
135
136impl std::error::Error for Error {}