Skip to main content

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::Incomplete`] for input that ends before the main header is whole,
5//! [`Error::Marker`] for an invalid field value, [`Error::FileFormat`] for a
6//! malformed JP2 box structure, [`Error::Unsupported`] for
7//! a valid-but-out-of-subset feature, [`Error::Limit`] for an input past a
8//! decoder resource guard, [`Error::InvalidOptions`] for bad caller options,
9//! and [`Error::Inconsistent`] for a violated internal invariant. Structural
10//! corruption anywhere in the pipeline — including packet headers and coded
11//! data — reports as [`Error::Codestream`].
12
13use core::fmt;
14
15use crate::WorkLimit;
16
17/// Crate result alias.
18pub type Result<T> = core::result::Result<T, Error>;
19
20/// A decode failure, tagged by the class of fault.
21///
22/// Match on the variant to decide what to do. The [`ErrorDetail`] inside
23/// holds a diagnostic for a log; its wording can change between releases, so
24/// do not parse it or compare it. [`Error::Limit`] holds a [`LimitDetail`]
25/// instead, which also says which limit refused the input and, when an
26/// option raises that limit, the [`WorkLimit`] to retry with. `Error` does
27/// not implement `PartialEq`: test the variant with `matches!`, and a limit
28/// by its [`LimitKind`]. Input that is not JPEG 2000 at all, plain text
29/// included, is [`Error::Codestream`]; empty input is [`Error::Incomplete`].
30///
31/// The variant also says what to tell a user:
32///
33/// | Variant | A message for a user |
34/// | ------- | -------------------- |
35/// | `Codestream` | The file is damaged, cut short or not a JPEG 2000 image. |
36/// | `Marker` | The file is damaged: a header field holds a value the standard does not allow. |
37/// | `FileFormat` | The file is damaged: its JP2 boxes are malformed or disagree with the image. |
38/// | `Incomplete` | The file is cut short before its header ends. If it is still arriving, try again with more of it, or feed it to an [`IncrementalDecoder`](crate::IncrementalDecoder). |
39/// | `Unsupported` | The file uses a JPEG 2000 feature this decoder does not read, or a valid request it does not do: sRGB output from sub-sampled sYCC chroma on an area smaller than the image (`DecodeOptions::region`). |
40/// | `Limit` | The file is larger or costlier than the decoder allows by default. If [`LimitDetail::retry_with`] gives a [`WorkLimit`], it can be retried with that limit raised. |
41/// | `InvalidOptions` | The decode options are invalid, for any file (`WorkLimit::Raised(0)`, `max_quality_layers` of `Some(0)`, sRGB output with `raw_channels` or `components`, an empty window, no component or one named twice) or for this one (a reduction past the file's levels, a window outside the image, a tile or component the image does not have, an area that holds no sample of a returned component at the reduction). |
42/// | `Inconsistent` | An internal error; please file a bug. |
43///
44/// Damage does not always show as the first row. A flipped bit in a header
45/// field can read as an absurd image size (`Limit`), an unknown marker or a
46/// feature the decoder does not read (`Unsupported`), so a corrupt file can
47/// come back as any of those. Do not retry a `Limit` with
48/// [`WorkLimit::Unlimited`](crate::WorkLimit::Unlimited) unless the source
49/// is trusted.
50///
51/// ```
52/// use rust_j2k::{Error, decode};
53///
54/// fn explain(error: &Error) -> &'static str {
55///     match error {
56///         Error::Codestream(_) | Error::Marker(_) | Error::FileFormat(_) => {
57///             "the file is damaged, truncated or not a JPEG 2000 image"
58///         }
59///         Error::Incomplete(_) => "the file is cut short before its header ends",
60///         Error::Unsupported(_) => "the file uses a feature this decoder does not read",
61///         Error::Limit(_) => "the file is larger or costlier than the decoder allows",
62///         Error::InvalidOptions(_) => "the decode options do not fit this file",
63///         // The enum is `#[non_exhaustive]`: a later version can add variants.
64///         _ => "the file could not be decoded",
65///     }
66/// }
67///
68/// let error = decode(b"hello").unwrap_err();
69/// assert!(matches!(error, Error::Codestream(_)));
70/// assert_eq!(
71///     explain(&error),
72///     "the file is damaged, truncated or not a JPEG 2000 image"
73/// );
74/// ```
75#[derive(Debug, Clone)]
76#[non_exhaustive]
77pub enum Error {
78    /// Not a JPEG 2000 codestream, or its structure is broken: a missing
79    /// segment, a segment too short for its fields, lost sync, a tile-part or
80    /// packet data cut short, or corrupt packet / coded data. Input that ends
81    /// before the main header is whole is [`Error::Incomplete`] instead. Any
82    /// input that is not JPEG 2000 at all (text, another image format) is
83    /// this variant, since it has no `SOC` marker.
84    Codestream(ErrorDetail),
85    /// The input ends before the codestream's main header is whole, that is,
86    /// before its first `SOT` marker (the start of the first
87    /// [tile-part](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/README.md#what-a-jpeg-2000-file-holds)) is complete. No top-level box or segment
88    /// the input holds in full was found damaged, so more bytes may still give
89    /// a valid header. The boxes inside a superbox (such as `ihdr` in `jp2h`)
90    /// are judged only once the superbox is whole, so a cut `jp2h` is this
91    /// variant even when its `ihdr` is already damaged.
92    ///
93    /// It begins with the empty input. A raw codestream is this variant from
94    /// 0 bytes up to its first `SOT` marker. A JP2 file is this variant from
95    /// 0 bytes as well: inside its signature box, at or inside any top-level
96    /// box before the `jp2c` box, inside the `jp2c` box header, and then in
97    /// the codestream's main header. A box inside a superbox, such as
98    /// `ihdr` in `jp2h`, is only read once the superbox is whole, so its faults
99    /// stay [`Error::FileFormat`].
100    ///
101    /// This is the "wait for more bytes" signal for a caller whose input
102    /// streams in. [`read_header`](crate::read_header) and
103    /// [`decode_with`](crate::decode_with) return it whether or not
104    /// [`strict`](crate::DecodeOptions::strict) is set, since every decode
105    /// needs the whole main header.
106    ///
107    /// The boxes and segments the input holds in full are judged first: a
108    /// damaged one gives an error, not this variant, usually the one the
109    /// whole file gives ([`Error::FileFormat`], [`Error::Codestream`],
110    /// [`Error::Marker`], [`Error::Unsupported`] or [`Error::Limit`]). So is
111    /// a box cut short whose type is already wrong, such as a second box that
112    /// is not `ftyp`. The whole file can give another one when a later
113    /// part of its header is broken too. The checks that tie segments to each
114    /// other or to the JP2 boxes wait for the whole header (for example, a
115    /// missing `COD` or `QCD`, quantization coverage, 9/7 without
116    /// quantization, MCT geometry, `PPM` order, and `ihdr` against SIZ).
117    ///
118    /// For a file that is still arriving, an
119    /// [`IncrementalDecoder`](crate::IncrementalDecoder) waits for the header
120    /// itself: its `refine` returns `Ok(None)` while the header is not whole.
121    ///
122    /// If no more bytes are coming, the file is truncated. A box or segment
123    /// length that is damaged so that it reaches past the end of the input
124    /// looks the same as a cut, so it is this variant too. Input that can no
125    /// longer become JPEG 2000 is [`Error::Codestream`]: a byte that is not
126    /// the start of the `SOC` marker or of the JP2 signature box, for example.
127    ///
128    /// ```
129    /// use rust_j2k::{DecodeOptions, Error, decode_with, read_header};
130    ///
131    /// # let bytes = include_bytes!(concat!(
132    /// #     env!("CARGO_MANIFEST_DIR"),
133    /// #     "/tests/fixtures/jpeg2000_regular_latlon.j2k"
134    /// # )).to_vec();
135    /// # /*
136    /// let bytes = std::fs::read("image.j2k")?;
137    /// # */
138    /// // The first 40 bytes end inside the main header: wait for more.
139    /// assert!(matches!(read_header(&bytes[..40]), Err(Error::Incomplete(_))));
140    /// let options = DecodeOptions::default().with_strict(false);
141    /// assert!(matches!(
142    ///     decode_with(&bytes[..40], &options),
143    ///     Err(Error::Incomplete(_))
144    /// ));
145    /// // Once the main header is there, the header reads, and a decode with
146    /// // `strict` off gives the image the data holds.
147    /// assert!(read_header(&bytes[..600]).is_ok());
148    /// assert!(decode_with(&bytes[..600], &options).is_ok());
149    /// # Ok::<(), Box<dyn std::error::Error>>(())
150    /// ```
151    Incomplete(ErrorDetail),
152    /// A marker segment has an invalid field: a reserved value, a bad length
153    /// or an out-of-range value.
154    Marker(ErrorDetail),
155    /// The JP2 box structure or a box field is malformed: a box that runs past
156    /// the superbox holding it, a truncated box after the codestream, a
157    /// missing or misplaced required box, an invalid field value, or a box
158    /// that disagrees with the codestream.
159    FileFormat(ErrorDetail),
160    /// A valid-but-not-decoded feature: an HTJ2K code-block that needs more
161    /// than one HT coding pass set (`MULTIHT` in the `CAP` marker), a Part 2
162    /// extension, a marker or coding style outside the decoded subset, a JP2
163    /// box this decoder cannot apply, a file that is not JP2-compatible. It
164    /// is also a request the decoder does not do, such as sRGB output from a
165    /// file it cannot convert.
166    Unsupported(ErrorDetail),
167    /// The input exceeded one of the decoder's resource guards: a hostile or
168    /// absurd declaration (code-block count, precinct count, bit-plane depth)
169    /// past a cap, an image of more samples than the sample limit allows, or
170    /// work past the bound for the file's size (see [`decode`](crate::decode)).
171    /// It is not a missing feature (that is [`Error::Unsupported`]), and the
172    /// file may be valid.
173    ///
174    /// Three of these can be changed, each with a [`WorkLimit`](crate::WorkLimit):
175    /// the sample limit
176    /// ([`DecodeOptions::sample_limit`](crate::DecodeOptions::sample_limit)),
177    /// which holds the image area and the samples that palette expansion, sYCC
178    /// chroma replication and a monochrome ICC conversion produce; reading the
179    /// packet headers
180    /// ([`DecodeOptions::packet_work_limit`](crate::DecodeOptions::packet_work_limit));
181    /// and decoding the code-blocks
182    /// ([`DecodeOptions::code_block_work_limit`](crate::DecodeOptions::code_block_work_limit)).
183    /// For one of them, [`LimitDetail::kind`] names the limit, and
184    /// [`LimitDetail::retry_with`] gives the `WorkLimit` to retry with, which
185    /// the message names too. It is a hint (see
186    /// [`WorkLimit`](crate::WorkLimit)), not a measure of the file.
187    ///
188    /// The other guards have no option, so a file past one of them is refused
189    /// whatever the options. A tile may hold at most 2^20 code-blocks and
190    /// 2^18 precincts, and 32 progression order change (POC) volumes; a
191    /// code-block may have at most 30 bit-planes; and under a `sample_limit`
192    /// of `WorkLimit::Unlimited`, an image too large for the target to
193    /// address is still refused. For these, `retry_with` is `None`.
194    /// [`LimitDetail`] has an example that retries.
195    Limit(LimitDetail),
196    /// The caller passed [`DecodeOptions`](crate::DecodeOptions) that are
197    /// invalid for this codestream, or that are invalid whatever the input
198    /// (sRGB output with `raw_channels`, or a limit of `WorkLimit::Raised(0)`).
199    /// The input itself may be fine.
200    InvalidOptions(ErrorDetail),
201    /// A decoder invariant was violated (declared geometry and decoded state
202    /// disagreed where they never should); please file a bug.
203    Inconsistent(ErrorDetail),
204}
205
206impl fmt::Display for Error {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        match self {
209            Error::Codestream(d) => write!(f, "codestream: {d}"),
210            Error::Incomplete(d) => write!(f, "incomplete: {d}"),
211            Error::Marker(d) => write!(f, "marker: {d}"),
212            Error::FileFormat(d) => write!(f, "file format: {d}"),
213            Error::Unsupported(d) => write!(f, "unsupported: {d}"),
214            Error::Limit(d) => write!(f, "limit: {d}"),
215            Error::InvalidOptions(d) => write!(f, "invalid options: {d}"),
216            Error::Inconsistent(d) => write!(f, "decoder bug (please report it): {d}"),
217        }
218    }
219}
220
221impl Error {
222    /// The diagnostic, without the prefix that `Display` adds for the
223    /// variant. Its wording can change between releases, so do not parse it
224    /// or compare it.
225    ///
226    /// ```
227    /// let error = rust_j2k::decode(b"hello").unwrap_err();
228    /// assert_eq!(error.to_string(), format!("codestream: {}", error.message()));
229    /// ```
230    pub fn message(&self) -> &str {
231        match self {
232            Error::Codestream(d)
233            | Error::Incomplete(d)
234            | Error::Marker(d)
235            | Error::FileFormat(d)
236            | Error::Unsupported(d)
237            | Error::InvalidOptions(d)
238            | Error::Inconsistent(d) => d.message(),
239            Error::Limit(d) => d.message(),
240        }
241    }
242}
243
244impl std::error::Error for Error {}
245
246/// The constructors the decoder uses, one for each variant.
247impl Error {
248    pub(crate) fn codestream(message: impl Into<String>) -> Error {
249        Error::Codestream(ErrorDetail::new(message))
250    }
251
252    pub(crate) fn incomplete(message: impl Into<String>) -> Error {
253        Error::Incomplete(ErrorDetail::new(message))
254    }
255
256    pub(crate) fn marker(message: impl Into<String>) -> Error {
257        Error::Marker(ErrorDetail::new(message))
258    }
259
260    pub(crate) fn file_format(message: impl Into<String>) -> Error {
261        Error::FileFormat(ErrorDetail::new(message))
262    }
263
264    pub(crate) fn unsupported(message: impl Into<String>) -> Error {
265        Error::Unsupported(ErrorDetail::new(message))
266    }
267
268    pub(crate) fn invalid_options(message: impl Into<String>) -> Error {
269        Error::InvalidOptions(ErrorDetail::new(message))
270    }
271
272    pub(crate) fn inconsistent(message: impl Into<String>) -> Error {
273        Error::Inconsistent(ErrorDetail::new(message))
274    }
275
276    /// An [`Error::Limit`] for a `kind` that no option raises.
277    pub(crate) fn limit_fixed(kind: LimitKind, message: impl Into<String>) -> Error {
278        debug_assert!(!kind.is_adjustable(), "{kind:?} has an option");
279        Error::limit(kind, None, message.into())
280    }
281
282    /// An [`Error::Limit`] for an adjustable `kind`, where `retry_with` is
283    /// the limit that may admit the input.
284    pub(crate) fn limit_retry(
285        kind: LimitKind,
286        retry_with: WorkLimit,
287        message: impl Into<String>,
288    ) -> Error {
289        debug_assert!(kind.is_adjustable(), "{kind:?} has no option");
290        Error::limit(kind, Some(retry_with), message.into())
291    }
292
293    /// An [`Error::Limit`] for an adjustable `kind` whose refusal shows no
294    /// limit to retry with.
295    pub(crate) fn limit_unhinted(kind: LimitKind, message: impl Into<String>) -> Error {
296        debug_assert!(kind.is_adjustable(), "{kind:?} has no option");
297        Error::limit(kind, None, message.into())
298    }
299
300    fn limit(kind: LimitKind, retry_with: Option<WorkLimit>, message: String) -> Error {
301        debug_assert!(
302            names_its_data(kind, retry_with.as_ref(), &message),
303            "{kind:?}, {retry_with:?}: {message}"
304        );
305        Error::Limit(LimitDetail {
306            kind,
307            retry_with,
308            message,
309        })
310    }
311}
312
313/// Whether a limit's `message` says what its data does: the `retry_with`
314/// limit, if there is one, and then the option `kind` names. A limit with
315/// no option names none.
316fn names_its_data(kind: LimitKind, retry_with: Option<&WorkLimit>, message: &str) -> bool {
317    let option = match kind {
318        LimitKind::Samples => Some("`DecodeOptions::sample_limit`"),
319        LimitKind::PacketWork => Some("`DecodeOptions::packet_work_limit`"),
320        LimitKind::CodeBlockWork => Some("`DecodeOptions::code_block_work_limit`"),
321        _ => None,
322    };
323    let retry = match retry_with {
324        Some(WorkLimit::Raised(n)) => message.contains(&format!("`WorkLimit::Raised({n})`")),
325        Some(WorkLimit::Unlimited) => message.contains("only `WorkLimit::Unlimited`"),
326        Some(_) => false,
327        None => !message.contains("`WorkLimit::Raised("),
328    };
329    retry
330        && match option {
331            Some(option) => retry_with.is_none() || message.contains(option),
332            None => retry_with.is_none() && !message.contains("DecodeOptions::"),
333        }
334}
335
336/// What an [`Error`] other than [`Error::Limit`] carries: a diagnostic for a
337/// log.
338///
339/// [`Display`](fmt::Display) and [`message`](Self::message) give the text.
340/// Its wording can change between releases, so do not parse it or compare
341/// it.
342// The fields are private so that a source error can join later without a
343// break: held in an `Arc` it keeps `Clone`, and the auto traits hold as long
344// as the field is unwind-safe (an `AssertUnwindSafe` around it, as `anyhow`
345// does, since an error is read through `&` only).
346#[derive(Clone)]
347#[non_exhaustive]
348pub struct ErrorDetail {
349    message: String,
350}
351
352impl ErrorDetail {
353    fn new(message: impl Into<String>) -> Self {
354        ErrorDetail {
355            message: message.into(),
356        }
357    }
358
359    /// The diagnostic, without the prefix that the [`Error`]'s `Display`
360    /// adds for the variant.
361    pub fn message(&self) -> &str {
362        &self.message
363    }
364}
365
366impl fmt::Debug for ErrorDetail {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        fmt::Debug::fmt(&self.message, f)
369    }
370}
371
372impl fmt::Display for ErrorDetail {
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        f.write_str(&self.message)
375    }
376}
377
378/// What an [`Error::Limit`] carries: which limit refused the input, the
379/// [`WorkLimit`] to retry with when an option raises that limit, and a
380/// diagnostic for a log.
381///
382/// ```
383/// use rust_j2k::{DecodeOptions, Error, LimitKind, decode, decode_with};
384///
385/// // A file that asks for far more work than its size allows.
386/// # let bytes = include_bytes!(concat!(
387/// #     env!("CARGO_MANIFEST_DIR"),
388/// #     "/tests/fixtures/tier1_work_bound/t1bomb_1024_64_88.j2k"
389/// # )).to_vec();
390/// # /*
391/// let bytes = std::fs::read("image.j2k")?;
392/// # */
393/// let Err(Error::Limit(limit)) = decode(&bytes) else {
394///     panic!("expected the code-block work bound to refuse this file");
395/// };
396/// assert_eq!(limit.kind(), LimitKind::CodeBlockWork);
397/// # assert!(DecodeOptions::default().with_retry(&limit).is_some());
398/// match DecodeOptions::default().with_retry(&limit) {
399///     // An option raises this limit: retry with it raised.
400///     Some(options) => {
401///         let image = decode_with(&bytes, &options)?;
402///         println!("{}x{}", image.width, image.height);
403///     }
404///     // No option raises this limit (`limit.kind().is_adjustable()` is
405///     // false), or the refusal gave no factor: the file is refused
406///     // whatever the options.
407///     None => eprintln!("refused: {limit}"),
408/// }
409/// # Ok::<(), Box<dyn std::error::Error>>(())
410/// ```
411#[derive(Debug, Clone)]
412#[non_exhaustive]
413pub struct LimitDetail {
414    kind: LimitKind,
415    retry_with: Option<WorkLimit>,
416    message: String,
417}
418
419impl LimitDetail {
420    /// Which limit refused the input.
421    pub fn kind(&self) -> LimitKind {
422        self.kind
423    }
424
425    /// What to set the option that [`kind`](Self::kind) names to, for a
426    /// retry that may admit the input; `None` when no option raises this
427    /// limit.
428    ///
429    /// It is the [`WorkLimit`] the message names: a
430    /// [`Raised`](WorkLimit::Raised) factor, or
431    /// [`Unlimited`](WorkLimit::Unlimited) for an image past every factor.
432    /// It is worked out from what the refusal shows, so a retry with it can
433    /// still be refused, by this limit later in the file or by another
434    /// limit (see [`WorkLimit`]), or fail with another error once past it,
435    /// such as damage the limit stopped the decode before. It is also
436    /// `None` for a packet work refusal that shows no factor, such as one
437    /// while reading the header.
438    ///
439    /// [`DecodeOptions::with_retry`](crate::DecodeOptions::with_retry)
440    /// applies it to the option `kind` names.
441    pub fn retry_with(&self) -> Option<WorkLimit> {
442        self.retry_with.clone()
443    }
444
445    /// The diagnostic, without the `limit: ` prefix that the [`Error`]'s
446    /// `Display` adds. Do not parse it: [`kind`](Self::kind) and
447    /// [`retry_with`](Self::retry_with) hold its data.
448    pub fn message(&self) -> &str {
449        &self.message
450    }
451}
452
453impl fmt::Display for LimitDetail {
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        f.write_str(&self.message)
456    }
457}
458
459/// Which limit an [`Error::Limit`] names.
460///
461/// The first three are [`DecodeOptions`](crate::DecodeOptions) limits that
462/// a [`WorkLimit`] raises. No option raises the others, so they refuse the
463/// input whatever the options.
464#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
465#[non_exhaustive]
466pub enum LimitKind {
467    /// The sample limit,
468    /// [`DecodeOptions::sample_limit`](crate::DecodeOptions::sample_limit):
469    /// the image area, and the samples that palette expansion, sYCC chroma
470    /// replication and a monochrome ICC conversion produce.
471    Samples,
472    /// The packet work bound,
473    /// [`DecodeOptions::packet_work_limit`](crate::DecodeOptions::packet_work_limit),
474    /// on reading the packet headers.
475    PacketWork,
476    /// The code-block work bound,
477    /// [`DecodeOptions::code_block_work_limit`](crate::DecodeOptions::code_block_work_limit),
478    /// on decoding the code-blocks.
479    CodeBlockWork,
480    /// An image of more samples than the target can address, refused under
481    /// any sample limit.
482    AddressSpace,
483    /// A tile of more than 2^20 code-blocks.
484    TileCodeBlocks,
485    /// A tile of more than 2^18 precincts.
486    TilePrecincts,
487    /// A tile's progression order change (`POC`) volumes past a fixed cap:
488    /// more than 32 of them, or more packets than the decoder tracks for
489    /// them.
490    PocVolumes,
491    /// A code-block of more than 30 bit-planes.
492    BitPlanes,
493}
494
495impl LimitKind {
496    /// Whether a [`DecodeOptions`](crate::DecodeOptions) limit raises this
497    /// one: true for [`Samples`](Self::Samples),
498    /// [`PacketWork`](Self::PacketWork) and
499    /// [`CodeBlockWork`](Self::CodeBlockWork).
500    pub fn is_adjustable(self) -> bool {
501        matches!(
502            self,
503            LimitKind::Samples | LimitKind::PacketWork | LimitKind::CodeBlockWork
504        )
505    }
506}
507
508/// `result` with its error as its `Debug` text, so that two results compare
509/// by variant, data and message in a test: [`Error`] has no `PartialEq`.
510#[cfg(test)]
511pub(crate) fn keyed<T>(result: Result<T>) -> core::result::Result<T, String> {
512    result.map_err(|error| format!("{error:?}"))
513}
514
515/// Whether `error` is an [`Error::Limit`] for `kind` that no option raises,
516/// so that it gives no limit to retry with.
517#[cfg(test)]
518pub(crate) fn is_fixed_limit(error: &Error, kind: LimitKind) -> bool {
519    matches!(error, Error::Limit(limit) if limit.kind() == kind && limit.retry_with().is_none())
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525
526    // `keyed` compares errors by their `Debug` text, so that text must hold
527    // the variant, the message and a limit's data.
528    #[test]
529    fn debug_shows_the_variant_the_data_and_the_message() {
530        assert_eq!(
531            format!("{:?}", crate::decode(b"hello").unwrap_err()),
532            "Codestream(\"does not start with the `SOC` marker\")"
533        );
534        let limit = Error::limit_fixed(LimitKind::BitPlanes, "31 bit-planes");
535        assert_eq!(
536            format!("{limit:?}"),
537            "Limit(LimitDetail { kind: BitPlanes, retry_with: None, message: \"31 bit-planes\" })"
538        );
539    }
540
541    #[test]
542    fn message_drops_the_prefix() {
543        let error = Error::marker("reserved");
544        assert_eq!(error.to_string(), "marker: reserved");
545        assert_eq!(error.message(), "reserved");
546        let limit = Error::limit_fixed(LimitKind::PocVolumes, "33 volumes");
547        assert_eq!(limit.message(), "33 volumes");
548    }
549
550    #[test]
551    fn the_three_options_are_the_adjustable_kinds() {
552        use LimitKind::*;
553        for kind in [Samples, PacketWork, CodeBlockWork] {
554            assert!(kind.is_adjustable(), "{kind:?}");
555        }
556        for kind in [
557            AddressSpace,
558            TileCodeBlocks,
559            TilePrecincts,
560            PocVolumes,
561            BitPlanes,
562        ] {
563            assert!(!kind.is_adjustable(), "{kind:?}");
564        }
565    }
566}