j2k-native 0.7.1

Pure-Rust JPEG 2000 and HTJ2K codec engine for j2k
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Error types for JPEG 2000 codec operations.

use core::fmt;
use j2k_types::J2kEncodeStageError;

/// The main error type for JPEG 2000 decoding operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeError {
    /// Errors related to JP2 file format and box parsing.
    Format(FormatError),
    /// Errors related to codestream markers.
    Marker(MarkerError),
    /// Errors related to tile processing.
    Tile(TileError),
    /// Errors related to image dimensions and validation.
    Validation(ValidationError),
    /// Errors related to decoding operations.
    Decoding(DecodingError),
    /// Errors related to color space and component handling.
    Color(ColorError),
    /// Simultaneously live decode/container allocations exceed the shared cap.
    AllocationTooLarge {
        /// Allocation family or phase being checked.
        what: &'static str,
        /// Requested live bytes, saturated on arithmetic overflow.
        requested: usize,
        /// Maximum permitted live bytes.
        cap: usize,
    },
    /// The host allocator rejected a checked, cap-valid decode allocation.
    HostAllocationFailed {
        /// Allocation being attempted.
        what: &'static str,
        /// Requested allocation bytes, saturated on arithmetic overflow.
        bytes: usize,
    },
}

/// Backend-neutral classification used by codec adapters.
///
/// This preserves the small amount of structured information that adapters
/// need without requiring each adapter to match the complete native error
/// hierarchy independently.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeErrorClass {
    /// Input ended before a required fixed-size read.
    InputTooShort {
        /// Required byte count.
        need: usize,
        /// Available byte count.
        have: usize,
    },
    /// Input ended while reading a named segment.
    InputTruncatedAt {
        /// Byte offset where truncation was detected.
        offset: usize,
        /// Stable segment label.
        segment: &'static str,
    },
    /// The codestream or container uses an unsupported feature.
    Unsupported {
        /// Stable user-facing feature label.
        what: &'static str,
    },
    /// All other native decoder failures.
    Backend,
}

/// Error returned by native JPEG 2000 and HTJ2K encode operations.
///
/// The variants deliberately keep resource failures distinct from malformed
/// requests, accelerator failures, and generated-codestream validation. This
/// lets facade and transcode callers preserve actionable failure categories
/// without parsing display strings.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EncodeError {
    /// Caller-provided samples, geometry, metadata, or options are invalid.
    InvalidInput {
        /// Stable description of the invalid condition.
        what: &'static str,
    },
    /// The requested encode feature or shape is not implemented.
    Unsupported {
        /// Stable description of the unsupported condition.
        what: &'static str,
    },
    /// Checked arithmetic overflowed while planning an encode phase.
    ArithmeticOverflow {
        /// Name of the value or phase whose size overflowed.
        what: &'static str,
    },
    /// Simultaneously live host allocations would exceed the shared cap.
    AllocationTooLarge {
        /// Name of the encode phase being checked.
        what: &'static str,
        /// Checked requested live host bytes at the rejected allocation boundary.
        requested: usize,
        /// Maximum permitted live host bytes.
        cap: usize,
    },
    /// The allocator could not reserve a checked, cap-valid host allocation.
    HostAllocationFailed {
        /// Name of the allocation that failed.
        what: &'static str,
        /// Requested allocation bytes, saturated on element-size overflow.
        bytes: usize,
    },
    /// An optional encode-stage accelerator accepted work but failed it.
    Accelerator {
        /// Encode-stage operation that failed.
        operation: &'static str,
        /// Structured stage failure with an optional concrete backend source.
        source: J2kEncodeStageError,
    },
    /// A generated codestream failed the requested validation contract.
    CodestreamValidation {
        /// Stable validation failure detail.
        detail: &'static str,
    },
    /// Internal encode state violated an invariant.
    InternalInvariant {
        /// Stable description of the violated invariant.
        what: &'static str,
    },
}

impl DecodeError {
    /// Classify this error for a facade or accelerator adapter.
    #[must_use]
    pub const fn classify(&self) -> DecodeErrorClass {
        match *self {
            Self::Format(FormatError::TooShort { need, have }) => {
                DecodeErrorClass::InputTooShort { need, have }
            }
            Self::Format(FormatError::TruncatedAt { offset, segment }) => {
                DecodeErrorClass::InputTruncatedAt { offset, segment }
            }
            Self::Format(FormatError::Unsupported) => DecodeErrorClass::Unsupported {
                what: "JP2 image format",
            },
            Self::Marker(MarkerError::Unsupported) => DecodeErrorClass::Unsupported {
                what: "JPEG 2000 marker",
            },
            Self::Decoding(DecodingError::DirectPlanUnsupported(reason)) => {
                DecodeErrorClass::Unsupported {
                    what: direct_plan_unsupported_what(reason),
                }
            }
            Self::Decoding(DecodingError::UnsupportedFeature(what)) => {
                DecodeErrorClass::Unsupported { what }
            }
            Self::Decoding(DecodingError::UnexpectedEof) => DecodeErrorClass::InputTruncatedAt {
                offset: 0,
                segment: "JPEG 2000 entropy data",
            },
            _ => DecodeErrorClass::Backend,
        }
    }
}

/// Errors related to JP2 file format and box parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormatError {
    /// Input ended before a required fixed-size box read.
    TooShort {
        /// Required byte count.
        need: usize,
        /// Available byte count.
        have: usize,
    },
    /// Input ended while reading a named box segment.
    TruncatedAt {
        /// Byte offset where truncation was detected.
        offset: usize,
        /// Name of the segment being read.
        segment: &'static str,
    },
    /// Invalid JP2 signature.
    InvalidSignature,
    /// Invalid JP2 file type.
    InvalidFileType,
    /// Invalid or malformed JP2 box.
    InvalidBox,
    /// Required JP2 box is absent.
    MissingRequiredBox(&'static str),
    /// Missing codestream data.
    MissingCodestream,
    /// Unsupported JP2 image format.
    Unsupported,
}

/// Errors related to codestream markers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarkerError {
    /// Invalid marker encountered.
    Invalid,
    /// Unsupported marker encountered.
    Unsupported,
    /// Expected a specific marker.
    Expected(&'static str),
    /// Missing a required marker.
    Missing(&'static str),
    /// Failed to read or parse a marker.
    ParseFailure(&'static str),
}

/// Errors related to tile processing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TileError {
    /// Invalid image tile was encountered.
    Invalid,
    /// Invalid tile index in tile-part header.
    InvalidIndex,
    /// Invalid tile or image offsets.
    InvalidOffsets,
    /// PPT marker present when PPM marker exists in main header.
    PpmPptConflict,
}

/// Errors related to image dimensions and validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ValidationError {
    /// Invalid image dimensions.
    InvalidDimensions,
    /// Image dimensions exceed supported limits.
    ImageTooLarge,
    /// Image has too many channels.
    TooManyChannels,
    /// The SIZ tile grid implies more tiles than any conforming codestream can address.
    TooManyTiles,
    /// Invalid component metadata.
    InvalidComponentMetadata,
    /// Invalid JP2 channel definition metadata.
    InvalidChannelDefinition,
    /// Invalid progression order.
    InvalidProgressionOrder,
    /// Invalid transformation type.
    InvalidTransformation,
    /// Invalid quantization style.
    InvalidQuantizationStyle,
    /// Missing exponents for precinct sizes.
    MissingPrecinctExponents,
    /// Not enough exponents provided in header.
    InsufficientExponents,
    /// Missing exponent step size.
    MissingStepSize,
    /// Invalid quantization exponents.
    InvalidExponents,
}

/// Errors related to decoding operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodingError {
    /// An error occurred while decoding a code-block.
    CodeBlockDecodeFailure,
    /// A backend-specific code-block decode failure with user-visible context.
    CodeBlockDecodeFailureWithContext(&'static str),
    /// A direct-plan builder rejected an unsupported image or codestream shape.
    DirectPlanUnsupported(DirectPlanUnsupportedReason),
    /// The codestream uses a feature that this decoder does not implement yet.
    UnsupportedFeature(&'static str),
    /// Number of bitplanes in a code-block is too large.
    TooManyBitplanes,
    /// A code-block contains too many coding passes.
    TooManyCodingPasses,
    /// Invalid number of bitplanes in a code-block.
    InvalidBitplaneCount,
    /// A precinct was invalid.
    InvalidPrecinct,
    /// A progression iterator ver invalid.
    InvalidProgressionIterator,
    /// Unexpected end of data.
    UnexpectedEof,
    /// Caller-provided output buffer is too small for the decoded image.
    OutputBufferTooSmall,
    /// A bounded host decode workspace could not be allocated.
    HostAllocationFailed,
}

/// Errors related to color space and component handling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ColorError {
    /// Multi-component transform failed.
    Mct,
    /// Failed to resolve palette indices.
    PaletteResolutionFailed,
    /// Failed to convert from sYCC to RGB.
    SyccConversionFailed,
    /// Failed to convert from LAB to RGB.
    LabConversionFailed,
}

/// Structured reasons why a direct JPEG 2000 device plan cannot be built.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectPlanUnsupportedReason {
    /// Grayscale direct plans require grayscale images without alpha.
    GrayscaleImageWithoutAlpha,
    /// Grayscale direct plans require a single-tile codestream.
    GrayscaleSingleTileCodestream,
    /// Grayscale direct plans require a single-component codestream.
    GrayscaleSingleComponentCodestream,
    /// Color direct plans require RGB images without alpha.
    ColorRgbImageWithoutAlpha,
    /// Color direct plans require a single-tile codestream.
    ColorSingleTileCodestream,
    /// Color direct plans require three RGB components.
    ColorThreeComponentRgbCodestream,
    /// A direct component plan index did not exist.
    ComponentIndexOutOfRange,
    /// Direct component plans require unit-sampled components.
    ComponentUnitSampled,
    /// A direct component decomposition index did not exist.
    ComponentDecompositionIndexOutOfRange,
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Format(e) => write!(f, "{e}"),
            Self::Marker(e) => write!(f, "{e}"),
            Self::Tile(e) => write!(f, "{e}"),
            Self::Validation(e) => write!(f, "{e}"),
            Self::Decoding(e) => write!(f, "{e}"),
            Self::Color(e) => write!(f, "{e}"),
            Self::AllocationTooLarge {
                what,
                requested,
                cap,
            } => write!(
                f,
                "{what} requires {requested} live host bytes, exceeding the {cap}-byte cap"
            ),
            Self::HostAllocationFailed { what, bytes } => {
                write!(
                    f,
                    "host allocation failed for {bytes} bytes while allocating {what}"
                )
            }
        }
    }
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidInput { what } => write!(f, "invalid encode input: {what}"),
            Self::Unsupported { what } => write!(f, "unsupported encode request: {what}"),
            Self::ArithmeticOverflow { what } => {
                write!(f, "encode size overflow while planning {what}")
            }
            Self::AllocationTooLarge {
                what,
                requested,
                cap,
            } => write!(
                f,
                "{what} requires {requested} live host bytes, exceeding the {cap}-byte cap"
            ),
            Self::HostAllocationFailed { what, bytes } => {
                write!(
                    f,
                    "host allocation failed for {bytes} bytes while allocating {what}"
                )
            }
            Self::Accelerator { operation, source } => {
                write!(f, "encode accelerator failed during {operation}: {source}")
            }
            Self::CodestreamValidation { detail } => {
                write!(f, "generated codestream validation failed: {detail}")
            }
            Self::InternalInvariant { what } => {
                write!(f, "native encode invariant failed: {what}")
            }
        }
    }
}

impl fmt::Display for FormatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooShort { need, have } => {
                write!(f, "input too short: need {need} bytes, have {have}")
            }
            Self::TruncatedAt { offset, segment } => {
                write!(
                    f,
                    "input truncated at offset {offset} while reading {segment}"
                )
            }
            Self::InvalidSignature => write!(f, "invalid JP2 signature"),
            Self::InvalidFileType => write!(f, "invalid JP2 file type"),
            Self::InvalidBox => write!(f, "invalid JP2 box"),
            Self::MissingRequiredBox(box_type) => write!(f, "missing required JP2 box {box_type}"),
            Self::MissingCodestream => write!(f, "missing codestream data"),
            Self::Unsupported => write!(f, "unsupported JP2 image"),
        }
    }
}

impl fmt::Display for MarkerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Invalid => write!(f, "invalid marker"),
            Self::Unsupported => write!(f, "unsupported marker"),
            Self::Expected(marker) => write!(f, "expected {marker} marker"),
            Self::Missing(marker) => write!(f, "missing {marker} marker"),
            Self::ParseFailure(marker) => write!(f, "failed to parse {marker} marker"),
        }
    }
}

impl fmt::Display for TileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Invalid => write!(f, "image contains no tiles"),
            Self::InvalidIndex => write!(f, "invalid tile index in tile-part header"),
            Self::InvalidOffsets => write!(f, "invalid tile offsets"),
            Self::PpmPptConflict => {
                write!(
                    f,
                    "PPT marker present when PPM marker exists in main header"
                )
            }
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidDimensions => write!(f, "invalid image dimensions"),
            Self::ImageTooLarge => write!(f, "image is too large"),
            Self::TooManyChannels => write!(f, "image has too many channels"),
            Self::TooManyTiles => write!(f, "image has too many tiles"),
            Self::InvalidComponentMetadata => write!(f, "invalid component metadata"),
            Self::InvalidChannelDefinition => write!(f, "invalid channel definition"),
            Self::InvalidProgressionOrder => write!(f, "invalid progression order"),
            Self::InvalidTransformation => write!(f, "invalid transformation type"),
            Self::InvalidQuantizationStyle => write!(f, "invalid quantization style"),
            Self::MissingPrecinctExponents => {
                write!(f, "missing exponents for precinct sizes")
            }
            Self::InsufficientExponents => {
                write!(f, "not enough exponents provided in header")
            }
            Self::MissingStepSize => write!(f, "missing exponent step size"),
            Self::InvalidExponents => write!(f, "invalid quantization exponents"),
        }
    }
}

impl fmt::Display for DecodingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CodeBlockDecodeFailure => write!(f, "failed to decode code-block"),
            Self::CodeBlockDecodeFailureWithContext(context) => {
                write!(f, "failed to decode code-block: {context}")
            }
            Self::DirectPlanUnsupported(reason) => {
                write!(f, "unsupported decoding feature: {reason}")
            }
            Self::UnsupportedFeature(feature) => {
                write!(f, "unsupported decoding feature: {feature}")
            }
            Self::TooManyBitplanes => write!(f, "number of bitplanes is too large"),
            Self::TooManyCodingPasses => {
                write!(f, "code-block contains too many coding passes")
            }
            Self::InvalidBitplaneCount => write!(f, "invalid number of bitplanes"),
            Self::InvalidPrecinct => write!(f, "a precinct was invalid"),
            Self::InvalidProgressionIterator => {
                write!(f, "a progression iterator was invalid")
            }
            Self::UnexpectedEof => write!(f, "unexpected end of data"),
            Self::OutputBufferTooSmall => write!(f, "output buffer is too small"),
            Self::HostAllocationFailed => write!(f, "host decode workspace allocation failed"),
        }
    }
}

impl fmt::Display for DirectPlanUnsupportedReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(direct_plan_unsupported_what(*self))
    }
}

const fn direct_plan_unsupported_what(reason: DirectPlanUnsupportedReason) -> &'static str {
    match reason {
        DirectPlanUnsupportedReason::GrayscaleImageWithoutAlpha => {
            "direct grayscale plan only supports grayscale images without alpha"
        }
        DirectPlanUnsupportedReason::GrayscaleSingleTileCodestream => {
            "direct grayscale plan only supports single-tile codestreams"
        }
        DirectPlanUnsupportedReason::GrayscaleSingleComponentCodestream => {
            "direct grayscale plan only supports single-component codestreams"
        }
        DirectPlanUnsupportedReason::ColorRgbImageWithoutAlpha => {
            "direct color plan only supports RGB images without alpha"
        }
        DirectPlanUnsupportedReason::ColorSingleTileCodestream => {
            "direct color plan only supports single-tile codestreams"
        }
        DirectPlanUnsupportedReason::ColorThreeComponentRgbCodestream => {
            "direct color plan only supports three-component RGB codestreams"
        }
        DirectPlanUnsupportedReason::ComponentIndexOutOfRange => {
            "direct component plan index is out of range"
        }
        DirectPlanUnsupportedReason::ComponentUnitSampled => {
            "direct component plan only supports unit-sampled components"
        }
        DirectPlanUnsupportedReason::ComponentDecompositionIndexOutOfRange => {
            "direct component decomposition index is out of range"
        }
    }
}

impl fmt::Display for ColorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Mct => write!(f, "multi-component transform failed"),
            Self::PaletteResolutionFailed => write!(f, "failed to resolve palette indices"),
            Self::SyccConversionFailed => write!(f, "failed to convert from sYCC to RGB"),
            Self::LabConversionFailed => write!(f, "failed to convert from LAB to RGB"),
        }
    }
}

impl core::error::Error for DecodeError {}
impl core::error::Error for EncodeError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Accelerator { source, .. } => Some(source),
            _ => None,
        }
    }
}
impl core::error::Error for FormatError {}
impl core::error::Error for MarkerError {}
impl core::error::Error for TileError {}
impl core::error::Error for ValidationError {}
impl core::error::Error for DecodingError {}
impl core::error::Error for DirectPlanUnsupportedReason {}
impl core::error::Error for ColorError {}

impl From<FormatError> for DecodeError {
    fn from(e: FormatError) -> Self {
        Self::Format(e)
    }
}

impl From<MarkerError> for DecodeError {
    fn from(e: MarkerError) -> Self {
        Self::Marker(e)
    }
}

impl From<TileError> for DecodeError {
    fn from(e: TileError) -> Self {
        Self::Tile(e)
    }
}

impl From<ValidationError> for DecodeError {
    fn from(e: ValidationError) -> Self {
        Self::Validation(e)
    }
}

impl From<DecodingError> for DecodeError {
    fn from(e: DecodingError) -> Self {
        Self::Decoding(e)
    }
}

impl From<ColorError> for DecodeError {
    fn from(e: ColorError) -> Self {
        Self::Color(e)
    }
}

/// Result type for JPEG 2000 decoding operations.
pub type Result<T> = core::result::Result<T, DecodeError>;

/// Result type for JPEG 2000 and HTJ2K encoding operations.
pub type EncodeResult<T> = core::result::Result<T, EncodeError>;

macro_rules! bail {
    ($err:expr) => {
        return Err($err.into())
    };
}

macro_rules! err {
    ($err:expr) => {
        Err($err.into())
    };
}

pub(crate) use bail;
pub(crate) use err;

#[cfg(test)]
mod classification_tests {
    use alloc::string::ToString;

    use super::{
        DecodeError, DecodeErrorClass, DecodingError, DirectPlanUnsupportedReason, EncodeError,
        FormatError, MarkerError, ValidationError,
    };

    #[test]
    fn facade_classification_preserves_structured_input_and_support_details() {
        let cases = [
            (
                DecodeError::Format(FormatError::TooShort { need: 9, have: 3 }),
                DecodeErrorClass::InputTooShort { need: 9, have: 3 },
            ),
            (
                DecodeError::Format(FormatError::TruncatedAt {
                    offset: 17,
                    segment: "SIZ",
                }),
                DecodeErrorClass::InputTruncatedAt {
                    offset: 17,
                    segment: "SIZ",
                },
            ),
            (
                DecodeError::Format(FormatError::Unsupported),
                DecodeErrorClass::Unsupported {
                    what: "JP2 image format",
                },
            ),
            (
                DecodeError::Marker(MarkerError::Unsupported),
                DecodeErrorClass::Unsupported {
                    what: "JPEG 2000 marker",
                },
            ),
            (
                DecodeError::Decoding(DecodingError::UnsupportedFeature("packet marker")),
                DecodeErrorClass::Unsupported {
                    what: "packet marker",
                },
            ),
            (
                DecodeError::Decoding(DecodingError::UnexpectedEof),
                DecodeErrorClass::InputTruncatedAt {
                    offset: 0,
                    segment: "JPEG 2000 entropy data",
                },
            ),
            (
                DecodeError::Validation(ValidationError::InvalidDimensions),
                DecodeErrorClass::Backend,
            ),
        ];

        for (error, expected) in cases {
            assert_eq!(error.classify(), expected, "{error}");
        }
    }

    #[test]
    fn direct_plan_classification_and_display_share_the_same_label() {
        let reason = DirectPlanUnsupportedReason::ColorThreeComponentRgbCodestream;
        let error = DecodeError::Decoding(DecodingError::DirectPlanUnsupported(reason));
        let DecodeErrorClass::Unsupported { what } = error.classify() else {
            panic!("direct-plan errors must classify as unsupported");
        };

        assert_eq!(what, reason.to_string());
    }

    #[test]
    fn encode_resource_errors_keep_cap_and_allocator_failures_distinct() {
        let cap_error = EncodeError::AllocationTooLarge {
            what: "Tier-2 packet assembly",
            requested: 513,
            cap: 512,
        };
        let allocation_error = EncodeError::HostAllocationFailed {
            what: "Tier-2 packet body",
            bytes: 511,
        };

        assert!(cap_error.to_string().contains("513"));
        assert!(cap_error.to_string().contains("512-byte cap"));
        assert!(allocation_error.to_string().contains("511"));
        assert_ne!(cap_error, allocation_error);
    }
}