Skip to main content

Error

Enum Error 

Source
#[non_exhaustive]
pub enum Error { Codestream(ErrorDetail), Incomplete(ErrorDetail), Marker(ErrorDetail), FileFormat(ErrorDetail), Unsupported(ErrorDetail), Limit(LimitDetail), InvalidOptions(ErrorDetail), Inconsistent(ErrorDetail), }
Expand description

A decode failure, tagged by the class of fault.

Match on the variant to decide what to do. The ErrorDetail inside holds a diagnostic for a log; its wording can change between releases, so do not parse it or compare it. Error::Limit holds a LimitDetail instead, which also says which limit refused the input and, when an option raises that limit, the WorkLimit to retry with. Error does not implement PartialEq: test the variant with matches!, and a limit by its LimitKind. Input that is not JPEG 2000 at all, plain text included, is Error::Codestream; empty input is Error::Incomplete.

The variant also says what to tell a user:

VariantA message for a user
CodestreamThe file is damaged, cut short or not a JPEG 2000 image.
MarkerThe file is damaged: a header field holds a value the standard does not allow.
FileFormatThe file is damaged: its JP2 boxes are malformed or disagree with the image.
IncompleteThe 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.
UnsupportedThe 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).
LimitThe 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.
InvalidOptionsThe 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).
InconsistentAn internal error; please file a bug.

Damage does not always show as the first row. A flipped bit in a header field can read as an absurd image size (Limit), an unknown marker or a feature the decoder does not read (Unsupported), so a corrupt file can come back as any of those. Do not retry a Limit with WorkLimit::Unlimited unless the source is trusted.

use rust_j2k::{Error, decode};

fn explain(error: &Error) -> &'static str {
    match error {
        Error::Codestream(_) | Error::Marker(_) | Error::FileFormat(_) => {
            "the file is damaged, truncated or not a JPEG 2000 image"
        }
        Error::Incomplete(_) => "the file is cut short before its header ends",
        Error::Unsupported(_) => "the file uses a feature this decoder does not read",
        Error::Limit(_) => "the file is larger or costlier than the decoder allows",
        Error::InvalidOptions(_) => "the decode options do not fit this file",
        // The enum is `#[non_exhaustive]`: a later version can add variants.
        _ => "the file could not be decoded",
    }
}

let error = decode(b"hello").unwrap_err();
assert!(matches!(error, Error::Codestream(_)));
assert_eq!(
    explain(&error),
    "the file is damaged, truncated or not a JPEG 2000 image"
);

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Codestream(ErrorDetail)

Not a JPEG 2000 codestream, or its structure is broken: a missing segment, a segment too short for its fields, lost sync, a tile-part or packet data cut short, or corrupt packet / coded data. Input that ends before the main header is whole is Error::Incomplete instead. Any input that is not JPEG 2000 at all (text, another image format) is this variant, since it has no SOC marker.

§

Incomplete(ErrorDetail)

The input ends before the codestream’s main header is whole, that is, before its first SOT marker (the start of the first tile-part) is complete. No top-level box or segment the input holds in full was found damaged, so more bytes may still give a valid header. The boxes inside a superbox (such as ihdr in jp2h) are judged only once the superbox is whole, so a cut jp2h is this variant even when its ihdr is already damaged.

It begins with the empty input. A raw codestream is this variant from 0 bytes up to its first SOT marker. A JP2 file is this variant from 0 bytes as well: inside its signature box, at or inside any top-level box before the jp2c box, inside the jp2c box header, and then in the codestream’s main header. A box inside a superbox, such as ihdr in jp2h, is only read once the superbox is whole, so its faults stay Error::FileFormat.

This is the “wait for more bytes” signal for a caller whose input streams in. read_header and decode_with return it whether or not strict is set, since every decode needs the whole main header.

The boxes and segments the input holds in full are judged first: a damaged one gives an error, not this variant, usually the one the whole file gives (Error::FileFormat, Error::Codestream, Error::Marker, Error::Unsupported or Error::Limit). So is a box cut short whose type is already wrong, such as a second box that is not ftyp. The whole file can give another one when a later part of its header is broken too. The checks that tie segments to each other or to the JP2 boxes wait for the whole header (for example, a missing COD or QCD, quantization coverage, 9/7 without quantization, MCT geometry, PPM order, and ihdr against SIZ).

For a file that is still arriving, an IncrementalDecoder waits for the header itself: its refine returns Ok(None) while the header is not whole.

If no more bytes are coming, the file is truncated. A box or segment length that is damaged so that it reaches past the end of the input looks the same as a cut, so it is this variant too. Input that can no longer become JPEG 2000 is Error::Codestream: a byte that is not the start of the SOC marker or of the JP2 signature box, for example.

use rust_j2k::{DecodeOptions, Error, decode_with, read_header};

let bytes = std::fs::read("image.j2k")?;
// The first 40 bytes end inside the main header: wait for more.
assert!(matches!(read_header(&bytes[..40]), Err(Error::Incomplete(_))));
let options = DecodeOptions::default().with_strict(false);
assert!(matches!(
    decode_with(&bytes[..40], &options),
    Err(Error::Incomplete(_))
));
// Once the main header is there, the header reads, and a decode with
// `strict` off gives the image the data holds.
assert!(read_header(&bytes[..600]).is_ok());
assert!(decode_with(&bytes[..600], &options).is_ok());
§

Marker(ErrorDetail)

A marker segment has an invalid field: a reserved value, a bad length or an out-of-range value.

§

FileFormat(ErrorDetail)

The JP2 box structure or a box field is malformed: a box that runs past the superbox holding it, a truncated box after the codestream, a missing or misplaced required box, an invalid field value, or a box that disagrees with the codestream.

§

Unsupported(ErrorDetail)

A valid-but-not-decoded feature: an HTJ2K code-block that needs more than one HT coding pass set (MULTIHT in the CAP marker), a Part 2 extension, a marker or coding style outside the decoded subset, a JP2 box this decoder cannot apply, a file that is not JP2-compatible. It is also a request the decoder does not do, such as sRGB output from a file it cannot convert.

§

Limit(LimitDetail)

The input exceeded one of the decoder’s resource guards: a hostile or absurd declaration (code-block count, precinct count, bit-plane depth) past a cap, an image of more samples than the sample limit allows, or work past the bound for the file’s size (see decode). It is not a missing feature (that is Error::Unsupported), and the file may be valid.

Three of these can be changed, each with a WorkLimit: the sample limit (DecodeOptions::sample_limit), which holds the image area and the samples that palette expansion, sYCC chroma replication and a monochrome ICC conversion produce; reading the packet headers (DecodeOptions::packet_work_limit); and decoding the code-blocks (DecodeOptions::code_block_work_limit). For one of them, LimitDetail::kind names the limit, and LimitDetail::retry_with gives the WorkLimit to retry with, which the message names too. It is a hint (see WorkLimit), not a measure of the file.

The other guards have no option, so a file past one of them is refused whatever the options. A tile may hold at most 2^20 code-blocks and 2^18 precincts, and 32 progression order change (POC) volumes; a code-block may have at most 30 bit-planes; and under a sample_limit of WorkLimit::Unlimited, an image too large for the target to address is still refused. For these, retry_with is None. LimitDetail has an example that retries.

§

InvalidOptions(ErrorDetail)

The caller passed DecodeOptions that are invalid for this codestream, or that are invalid whatever the input (sRGB output with raw_channels, or a limit of WorkLimit::Raised(0)). The input itself may be fine.

§

Inconsistent(ErrorDetail)

A decoder invariant was violated (declared geometry and decoded state disagreed where they never should); please file a bug.

Implementations§

Source§

impl Error

Source

pub fn message(&self) -> &str

The diagnostic, without the prefix that Display adds for the variant. Its wording can change between releases, so do not parse it or compare it.

let error = rust_j2k::decode(b"hello").unwrap_err();
assert_eq!(error.to_string(), format!("codestream: {}", error.message()));

Trait Implementations§

Source§

impl Clone for Error

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementations§

§

impl Forget for Error

§

impl Freeze for Error

§

impl Move for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.