Skip to main content

jbig2_decoder/
error.rs

1use core::fmt;
2use std::io;
3#[cfg(verus_keep_ghost)]
4use vstd::prelude::*;
5#[cfg(verus_keep_ghost)]
6use vstd::std_specs::convert::FromSpecImpl;
7
8/// Stable deterministic I/O failure classification.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[non_exhaustive]
11#[cfg_attr(verus_keep_ghost, verus_verify)]
12pub enum IoErrorKind {
13    /// Requested input was not found.
14    NotFound,
15    /// Input access was denied.
16    PermissionDenied,
17    /// A connection was refused.
18    ConnectionRefused,
19    /// A connection was reset.
20    ConnectionReset,
21    /// A connection was aborted.
22    ConnectionAborted,
23    /// An input source is not connected.
24    NotConnected,
25    /// An address is already in use.
26    AddressInUse,
27    /// An address is unavailable.
28    AddressNotAvailable,
29    /// A pipe was closed.
30    BrokenPipe,
31    /// A resource already exists.
32    AlreadyExists,
33    /// The operation would block.
34    WouldBlock,
35    /// An I/O argument is invalid.
36    InvalidInput,
37    /// Input data is invalid.
38    InvalidData,
39    /// The operation timed out.
40    TimedOut,
41    /// A write produced no bytes.
42    WriteZero,
43    /// The operation was interrupted.
44    Interrupted,
45    /// The operation is unsupported.
46    Unsupported,
47    /// Input ended unexpectedly.
48    UnexpectedEof,
49    /// The operating system reported memory exhaustion.
50    OutOfMemory,
51    /// Any unclassified I/O failure.
52    Other,
53}
54
55impl From<io::ErrorKind> for IoErrorKind {
56    fn from(kind: io::ErrorKind) -> Self {
57        match kind {
58            io::ErrorKind::NotFound => Self::NotFound,
59            io::ErrorKind::PermissionDenied => Self::PermissionDenied,
60            io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,
61            io::ErrorKind::ConnectionReset => Self::ConnectionReset,
62            io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,
63            io::ErrorKind::NotConnected => Self::NotConnected,
64            io::ErrorKind::AddrInUse => Self::AddressInUse,
65            io::ErrorKind::AddrNotAvailable => Self::AddressNotAvailable,
66            io::ErrorKind::BrokenPipe => Self::BrokenPipe,
67            io::ErrorKind::AlreadyExists => Self::AlreadyExists,
68            io::ErrorKind::WouldBlock => Self::WouldBlock,
69            io::ErrorKind::InvalidInput => Self::InvalidInput,
70            io::ErrorKind::InvalidData => Self::InvalidData,
71            io::ErrorKind::TimedOut => Self::TimedOut,
72            io::ErrorKind::WriteZero => Self::WriteZero,
73            io::ErrorKind::Interrupted => Self::Interrupted,
74            io::ErrorKind::Unsupported => Self::Unsupported,
75            io::ErrorKind::UnexpectedEof => Self::UnexpectedEof,
76            io::ErrorKind::OutOfMemory => Self::OutOfMemory,
77            _ => Self::Other,
78        }
79    }
80}
81
82/// Detailed malformed Huffman table or code classification.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84#[non_exhaustive]
85#[cfg_attr(verus_keep_ghost, verus_verify)]
86pub enum HuffmanErrorKind {
87    /// Reserved code-table flag bits were set.
88    ReservedFlags(u8),
89    /// The declared low/high bounds are invalid.
90    InvalidBounds {
91        /// Inclusive low bound.
92        low: i32,
93        /// Exclusive high bound.
94        high: i32,
95    },
96    /// A range suffix length exceeds 32 bits.
97    InvalidRangeLength(u8),
98    /// Normal ranges do not exactly partition the declared interval.
99    InvalidRangePartition,
100    /// Normal and special lines are not in normative order.
101    InvalidLineOrder,
102    /// A LOW, HIGH, or OOB line has invalid fields.
103    InvalidSpecialLine,
104    /// A special line occurs more than once.
105    DuplicateSpecialLine,
106    /// The table defines no decodable codes.
107    NoCodes,
108    /// Canonical prefix assignment exceeds the available code space.
109    Oversubscribed,
110    /// More than seven bits follow an encoded custom table.
111    TrailingBits(u64),
112    /// Encoded custom-table padding contains a one bit.
113    NonZeroPadding,
114    /// No table line matches the coded prefix.
115    InvalidCode,
116}
117
118/// Detailed malformed MMR stream classification.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120#[non_exhaustive]
121#[cfg_attr(verus_keep_ghost, verus_verify)]
122pub enum MmrErrorKind {
123    /// No two-dimensional mode matches the coded prefix.
124    InvalidMode {
125        /// Bit offset of the mode prefix.
126        bit_offset: usize,
127    },
128    /// T.6 extension modes are forbidden by JBIG2.
129    ExtensionMode {
130        /// Bit offset of the extension prefix.
131        bit_offset: usize,
132    },
133    /// No run code matches the selected colour and prefix.
134    InvalidRunCode {
135        /// Bit offset of the run prefix.
136        bit_offset: usize,
137        /// Whether the run is black.
138        black: bool,
139    },
140    /// A run exceeds the remaining row width.
141    RunExceedsRow,
142    /// A pass or vertical transition is out of bounds or moves backward.
143    InvalidTransition,
144    /// A mode fails to make semantic progress.
145    NonProgress,
146    /// A row uses more modes than its dimension-derived bound.
147    TooManyModes,
148    /// A required EOFB marker is absent.
149    MissingEofb,
150    /// EOFB bits do not match the normative marker.
151    InvalidEofb,
152    /// More than byte-alignment padding remains.
153    TrailingData,
154    /// Final byte-alignment padding contains a one bit.
155    NonZeroPadding,
156}
157
158/// Detailed malformed pattern-dictionary or halftone classification.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160#[non_exhaustive]
161#[cfg_attr(verus_keep_ghost, verus_verify)]
162pub enum HalftoneErrorKind {
163    /// Pattern dictionary flags are invalid.
164    InvalidPatternDictionaryFlags(u8),
165    /// Pattern dimensions are zero or otherwise invalid.
166    InvalidPatternDimensions {
167        /// Pattern width.
168        width: u8,
169        /// Pattern height.
170        height: u8,
171    },
172    /// Halftone flags are invalid.
173    InvalidHalftoneFlags(u8),
174    /// MMR/template/skip configuration is invalid.
175    InvalidConfiguration,
176    /// A callback returned a bitmap with unexpected dimensions.
177    InvalidBitmapDimensions {
178        /// Expected width.
179        expected_width: u32,
180        /// Expected height.
181        expected_height: u32,
182        /// Actual width.
183        actual_width: u32,
184        /// Actual height.
185        actual_height: u32,
186    },
187    /// Gray bit depth exceeds the supported 32-bit index domain.
188    InvalidGrayBitDepth(u8),
189    /// A halftone region references no patterns.
190    EmptyPatternDictionary,
191    /// Patterns do not share one fixed size.
192    InconsistentPatternDimensions,
193    /// A decoded gray index does not name a pattern.
194    InvalidPatternIndex {
195        /// Decoded pattern index.
196        index: u32,
197        /// Available pattern count.
198        pattern_count: u64,
199    },
200}
201
202/// Detailed malformed generic or refinement region classification.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204#[non_exhaustive]
205#[cfg_attr(verus_keep_ghost, verus_verify)]
206pub enum GenericRegionErrorKind {
207    /// Reserved generic/refinement flag bits are set.
208    ReservedFlags(u8),
209    /// A generic/refinement flag combination is invalid.
210    InvalidFlags(u8),
211    /// A target adaptive pixel does not name an earlier pixel.
212    InvalidAdaptivePixel {
213        /// One-based adaptive-pixel number.
214        number: u8,
215        /// Horizontal offset.
216        x: i32,
217        /// Vertical offset.
218        y: i32,
219    },
220    /// Skip bitmap dimensions do not match the target.
221    InvalidSkipDimensions,
222    /// An arithmetic bitmap lacks its FF AC terminator.
223    InvalidArithmeticTerminator,
224    /// An unexpected arithmetic marker was observed.
225    UnexpectedArithmeticMarker {
226        /// Marker prefix byte offset.
227        offset: usize,
228        /// Marker code byte.
229        code: u8,
230    },
231    /// Terminal row count differs from decoded rows.
232    RowCountMismatch {
233        /// Expected decoded rows.
234        expected: u32,
235        /// Terminal row count.
236        actual: u32,
237    },
238    /// A generated context index exceeds allocated statistics.
239    ContextIndex {
240        /// Generated context index.
241        index: usize,
242        /// Allocated context count.
243        count: usize,
244    },
245}
246
247/// A deterministic classification of malformed input.
248#[derive(Debug, PartialEq, Eq)]
249#[non_exhaustive]
250#[cfg_attr(verus_keep_ghost, verus_verify)]
251pub enum MalformedError {
252    /// The input ended before a complete value was available.
253    UnexpectedEof {
254        /// Byte or bit offset at which the read started.
255        offset: u64,
256        /// Number of bytes or bits requested.
257        needed: u64,
258        /// Number of bytes or bits that remained.
259        remaining: u64,
260    },
261    /// A standalone file did not start with the JBIG2 identifier.
262    InvalidFileSignature,
263    /// Reserved file-header flag bits were non-zero.
264    ReservedFileHeaderFlags(u8),
265    /// A bit read requested more than the supported 32 bits.
266    InvalidBitCount(u8),
267    /// A reserved segment type appeared in a segment header.
268    ReservedSegmentType(u8),
269    /// The three-bit referred-to count discriminator was reserved.
270    InvalidReferredToCountCode(u8),
271    /// Long-form referred-to counts were used for four or fewer references.
272    NonCanonicalReferredToCount(u32),
273    /// Unused retention bits were non-zero.
274    NonZeroUnusedRetentionFlags,
275    /// A segment referred to itself or a later-numbered segment.
276    InvalidReferredSegmentNumber {
277        /// Number of the segment containing the reference.
278        segment: u32,
279        /// Invalid referred-to segment number.
280        referred: u32,
281    },
282    /// An extension header violates reserved/necessary flag rules.
283    InvalidExtensionType(u32),
284    /// A defined comment extension is not correctly terminated.
285    InvalidCommentExtension,
286    /// Profiles metadata is misplaced, duplicated, or not restrictive enough.
287    InvalidProfilesSegment(u32),
288    /// A Huffman table or coded prefix is malformed.
289    InvalidHuffman(HuffmanErrorKind),
290    /// A restored arithmetic probability context is invalid.
291    InvalidArithmeticContextState {
292        /// Table E.1 state index.
293        state_index: u8,
294        /// More-probable symbol value.
295        mps: u8,
296    },
297    /// An arithmetic procedure was given too few probability contexts.
298    InsufficientArithmeticContexts {
299        /// Required number of contexts.
300        required: usize,
301        /// Supplied number of contexts.
302        actual: usize,
303    },
304    /// IAID code length cannot be represented safely.
305    InvalidIaidCodeLength(u8),
306    /// An MMR mode, run, transition, marker, or padding rule is invalid.
307    InvalidMmr(MmrErrorKind),
308    /// A symbol dictionary or text-region state-machine rule is invalid.
309    InvalidSymbolText(&'static str),
310    /// A decoded symbol ID does not name an available symbol.
311    SymbolIdOutOfRange {
312        /// Decoded symbol ID.
313        id: u32,
314        /// Number of available symbols.
315        available: u32,
316    },
317    /// Refined or collective symbol dimensions are invalid.
318    InvalidSymbolDimensions,
319    /// A pattern dictionary or halftone rule is invalid.
320    InvalidHalftone(HalftoneErrorKind),
321    /// A generic or refinement region rule is invalid.
322    InvalidGenericRegion(GenericRegionErrorKind),
323    /// Decoded segment order or page policy is inconsistent.
324    InvalidPageState(&'static str),
325    /// An unknown segment length appeared on a segment type that forbids it.
326    InvalidUnknownSegmentLength(u8),
327    /// A segment payload length did not match its fixed syntax.
328    InvalidSegmentDataLength {
329        /// Numeric segment type.
330        segment_type: u8,
331        /// Required number of bytes.
332        expected: u64,
333        /// Actual number of bytes.
334        actual: u64,
335    },
336    /// A reserved region information flag was set.
337    ReservedRegionFlags(u8),
338    /// A region selected an undefined external combination operator.
339    InvalidCombinationOperator(u8),
340    /// An unknown-height page was not marked as striped.
341    UnknownHeightWithoutStriping,
342    /// An end-of-stripe row exceeds its page or is not increasing.
343    InvalidStripeEndRow(u32),
344    /// Segment numbers are duplicated.
345    DuplicateSegmentNumber(u32),
346    /// Standalone segment headers are not in increasing number order.
347    NonIncreasingSegmentNumber {
348        /// Previous segment number.
349        previous: u32,
350        /// Current segment number.
351        current: u32,
352    },
353    /// A referred-to segment is absent from the available document state.
354    MissingReferredSegment {
355        /// Referring segment number.
356        segment: u32,
357        /// Missing segment number.
358        referred: u32,
359    },
360    /// A segment has an invalid global or page association.
361    InvalidPageAssociation {
362        /// Segment number.
363        segment: u32,
364        /// Page association.
365        page: u32,
366    },
367    /// A page's first associated segment was not page information.
368    MissingPageInformation(u32),
369    /// A page has duplicate page-information or end-of-page segments.
370    DuplicatePageBoundary {
371        /// Page number.
372        page: u32,
373        /// Boundary segment type.
374        segment_type: u8,
375    },
376    /// A segment associated with a page appeared after its end-of-page segment.
377    SegmentAfterEndOfPage {
378        /// Segment number.
379        segment: u32,
380        /// Page number.
381        page: u32,
382    },
383    /// A page did not end with an end-of-page segment.
384    MissingEndOfPage(u32),
385    /// A random-access file did not contain a final end-of-file header.
386    MissingEndOfFile,
387    /// Bytes occurred after a terminal end-of-file segment.
388    TrailingData(u64),
389    /// The declared page count differs from parsed pages.
390    PageCountMismatch {
391        /// Declared page count.
392        declared: u32,
393        /// Parsed page count.
394        actual: u32,
395    },
396    /// A fixed-length segment contains semantically invalid reference types.
397    InvalidSegmentReferences(u32),
398    /// An unknown-length generic region terminator was not found.
399    MissingGenericRegionTerminator,
400    /// An unknown-length generic region row count exceeds its declared height.
401    GenericRegionRowCount {
402        /// Declared region height.
403        declared: u32,
404        /// Encoded terminal row count.
405        actual: u32,
406    },
407    /// Retention flags permit discarding a segment before its final use.
408    InvalidRetentionFlags {
409        /// Segment carrying the invalid retention decision.
410        segment: u32,
411        /// Segment whose state would be discarded incorrectly.
412        referred: u32,
413    },
414    /// An input-derived arithmetic operation overflowed.
415    IntegerOverflow,
416}
417
418impl fmt::Display for MalformedError {
419    #[allow(clippy::too_many_lines)]
420    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
421        match self {
422            Self::UnexpectedEof {
423                offset,
424                needed,
425                remaining,
426            } => write!(
427                formatter,
428                "unexpected end of input at {offset}: needed {needed}, remaining {remaining}"
429            ),
430            Self::InvalidFileSignature => formatter.write_str("invalid JBIG2 file signature"),
431            Self::ReservedFileHeaderFlags(flags) => {
432                write!(
433                    formatter,
434                    "reserved JBIG2 file-header flags are set: {flags:#04x}"
435                )
436            }
437            Self::InvalidBitCount(count) => {
438                write!(formatter, "cannot read {count} bits into a 32-bit value")
439            }
440            Self::ReservedSegmentType(segment_type) => {
441                write!(formatter, "reserved JBIG2 segment type {segment_type}")
442            }
443            Self::InvalidReferredToCountCode(code) => {
444                write!(formatter, "reserved referred-to count code {code}")
445            }
446            Self::NonCanonicalReferredToCount(count) => {
447                write!(
448                    formatter,
449                    "long-form referred-to count used for short count {count}"
450                )
451            }
452            Self::NonZeroUnusedRetentionFlags => {
453                formatter.write_str("unused retention flag bits are non-zero")
454            }
455            Self::InvalidReferredSegmentNumber { segment, referred } => write!(
456                formatter,
457                "segment {segment} refers to non-preceding segment {referred}"
458            ),
459            Self::InvalidUnknownSegmentLength(segment_type) => write!(
460                formatter,
461                "unknown data length is invalid for segment type {segment_type}"
462            ),
463            Self::InvalidSegmentDataLength {
464                segment_type,
465                expected,
466                actual,
467            } => write!(
468                formatter,
469                "segment type {segment_type} requires {expected} data bytes, got {actual}"
470            ),
471            Self::ReservedRegionFlags(flags) => {
472                write!(formatter, "reserved region flags are set: {flags:#04x}")
473            }
474            Self::InvalidCombinationOperator(operator) => {
475                write!(formatter, "invalid combination operator {operator}")
476            }
477            Self::UnknownHeightWithoutStriping => {
478                formatter.write_str("unknown-height page is not striped")
479            }
480            Self::InvalidStripeEndRow(row) => {
481                write!(formatter, "invalid end-of-stripe row {row}")
482            }
483            Self::DuplicateSegmentNumber(segment) => {
484                write!(formatter, "duplicate segment number {segment}")
485            }
486            Self::NonIncreasingSegmentNumber { previous, current } => write!(
487                formatter,
488                "standalone segment number {current} does not follow {previous}"
489            ),
490            Self::MissingReferredSegment { segment, referred } => {
491                write!(
492                    formatter,
493                    "segment {segment} refers to missing segment {referred}"
494                )
495            }
496            Self::InvalidPageAssociation { segment, page } => {
497                write!(
498                    formatter,
499                    "segment {segment} has invalid page association {page}"
500                )
501            }
502            Self::MissingPageInformation(page) => {
503                write!(
504                    formatter,
505                    "page {page} does not start with page information"
506                )
507            }
508            Self::DuplicatePageBoundary { page, segment_type } => write!(
509                formatter,
510                "page {page} has duplicate boundary segment type {segment_type}"
511            ),
512            Self::SegmentAfterEndOfPage { segment, page } => {
513                write!(
514                    formatter,
515                    "segment {segment} occurs after end of page {page}"
516                )
517            }
518            Self::MissingEndOfPage(page) => {
519                write!(formatter, "page {page} has no end-of-page segment")
520            }
521            Self::MissingEndOfFile => {
522                formatter.write_str("random-access file has no final end-of-file segment")
523            }
524            Self::TrailingData(bytes) => {
525                write!(formatter, "{bytes} trailing bytes follow the JBIG2 stream")
526            }
527            Self::PageCountMismatch { declared, actual } => write!(
528                formatter,
529                "file declares {declared} pages but contains {actual}"
530            ),
531            Self::InvalidSegmentReferences(segment) => {
532                write!(
533                    formatter,
534                    "segment {segment} has invalid referred-to segment types"
535                )
536            }
537            Self::MissingGenericRegionTerminator => {
538                formatter.write_str("unknown-length generic region has no terminator")
539            }
540            Self::GenericRegionRowCount { declared, actual } => write!(
541                formatter,
542                "generic region row count {actual} exceeds declared height {declared}"
543            ),
544            Self::InvalidRetentionFlags { segment, referred } => write!(
545                formatter,
546                "segment {segment} has invalid retention flags for segment {referred}"
547            ),
548            Self::InvalidExtensionType(extension_type) => {
549                write!(formatter, "invalid extension type {extension_type:#010x}")
550            }
551            Self::InvalidCommentExtension => formatter.write_str("malformed comment extension"),
552            Self::InvalidProfilesSegment(segment) => {
553                write!(formatter, "invalid profiles segment {segment}")
554            }
555            Self::InvalidHuffman(kind) => {
556                write!(formatter, "invalid Huffman data: {kind:?}")
557            }
558            Self::InvalidArithmeticContextState { state_index, mps } => write!(
559                formatter,
560                "invalid arithmetic context state I={state_index}, MPS={mps}"
561            ),
562            Self::InsufficientArithmeticContexts { required, actual } => write!(
563                formatter,
564                "arithmetic decoding requires {required} contexts, got {actual}"
565            ),
566            Self::InvalidIaidCodeLength(length) => {
567                write!(formatter, "invalid IAID code length {length}")
568            }
569            Self::InvalidMmr(kind) => {
570                write!(formatter, "invalid MMR data: {kind:?}")
571            }
572            Self::InvalidSymbolText(reason) => {
573                write!(formatter, "invalid symbol/text data: {reason}")
574            }
575            Self::SymbolIdOutOfRange { id, available } => write!(
576                formatter,
577                "symbol ID {id} is outside {available} available symbols"
578            ),
579            Self::InvalidSymbolDimensions => formatter.write_str("invalid symbol dimensions"),
580            Self::InvalidHalftone(kind) => {
581                write!(formatter, "invalid halftone data: {kind:?}")
582            }
583            Self::InvalidGenericRegion(kind) => {
584                write!(formatter, "invalid generic-region data: {kind:?}")
585            }
586            Self::InvalidPageState(reason) => {
587                write!(formatter, "invalid page state: {reason}")
588            }
589            Self::IntegerOverflow => formatter.write_str("input-derived integer overflow"),
590        }
591    }
592}
593
594/// A feature that is valid JBIG2 syntax but outside the approved profile.
595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
596#[non_exhaustive]
597#[cfg_attr(verus_keep_ghost, verus_verify)]
598pub enum UnsupportedFeature {
599    /// Colour palette and coloured-region extensions.
600    Colour,
601    /// A recognized but unsupported segment type.
602    SegmentType(u8),
603    /// A necessary extension with an unknown type.
604    Extension(u32),
605}
606
607impl fmt::Display for UnsupportedFeature {
608    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
609        match self {
610            Self::Colour => formatter.write_str("JBIG2 colour extensions"),
611            Self::SegmentType(segment_type) => {
612                write!(formatter, "JBIG2 segment type {segment_type}")
613            }
614            Self::Extension(extension_type) => {
615                write!(
616                    formatter,
617                    "necessary JBIG2 extension {extension_type:#010x}"
618                )
619            }
620        }
621    }
622}
623
624/// The resource whose configured limit was exceeded.
625#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626#[non_exhaustive]
627#[cfg_attr(verus_keep_ghost, verus_verify)]
628pub enum LimitKind {
629    /// Page or region width.
630    Width,
631    /// Page or region height.
632    Height,
633    /// Pixels in one page or bitmap.
634    PagePixels,
635    /// Decoder-managed memory.
636    Memory,
637    /// Input stream bytes.
638    StreamBytes,
639    /// Number of pages.
640    Pages,
641    /// Number of segments.
642    Segments,
643    /// Number of symbols.
644    Symbols,
645    /// References on one segment.
646    ReferencesPerSegment,
647    /// References across the decode operation.
648    TotalReferences,
649    /// Reference graph depth.
650    ReferenceDepth,
651    /// Nested decoding depth.
652    NestingDepth,
653    /// Abstract work units.
654    Work,
655    /// Cumulative decoded bitmap bytes.
656    DecodedBitmapBytes,
657    /// Retained decoder state.
658    RetainedState,
659}
660
661impl fmt::Display for LimitKind {
662    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
663        write!(formatter, "{self:?}")
664    }
665}
666
667/// Details of a resource-limit failure.
668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
669#[cfg_attr(verus_keep_ghost, verus_verify)]
670pub struct LimitExceeded {
671    /// Resource that exceeded its limit.
672    pub kind: LimitKind,
673    /// Configured inclusive maximum.
674    pub limit: u64,
675    /// Input-derived value that exceeded the maximum.
676    pub actual: u64,
677}
678
679impl fmt::Display for LimitExceeded {
680    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
681        write!(
682            formatter,
683            "{} limit exceeded: maximum {}, actual {}",
684            self.kind, self.limit, self.actual
685        )
686    }
687}
688
689/// Error returned by parsing and decoding operations.
690#[derive(Debug)]
691#[non_exhaustive]
692#[cfg_attr(verus_keep_ghost, verus_verify)]
693pub enum DecodeError {
694    /// The input violates the JBIG2 syntax or semantics.
695    Malformed(MalformedError),
696    /// The input uses valid syntax outside the approved support matrix.
697    Unsupported(UnsupportedFeature),
698    /// An explicit resource limit was exceeded.
699    LimitExceeded(LimitExceeded),
700    /// A fallible allocation could not reserve the requested storage.
701    Allocation {
702        /// Requested allocation size in bytes.
703        requested_bytes: u64,
704    },
705    /// Reading from an input source failed.
706    Io(IoErrorKind),
707}
708
709impl fmt::Display for DecodeError {
710    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
711        match self {
712            Self::Malformed(error) => write!(formatter, "malformed JBIG2 input: {error}"),
713            Self::Unsupported(feature) => {
714                write!(formatter, "unsupported JBIG2 feature: {feature}")
715            }
716            Self::LimitExceeded(error) => error.fmt(formatter),
717            Self::Allocation { requested_bytes } => {
718                write!(formatter, "failed to allocate {requested_bytes} bytes")
719            }
720            Self::Io(kind) => write!(formatter, "input/output error: {kind:?}"),
721        }
722    }
723}
724
725impl std::error::Error for DecodeError {
726    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
727        None
728    }
729}
730
731impl DecodeError {
732    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
733        ensures out == DecodeError::Malformed(error),
734    ))]
735    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
736    fn from_malformed(error: MalformedError) -> Self {
737        Self::Malformed(error)
738    }
739
740    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
741        ensures out == DecodeError::LimitExceeded(error),
742    ))]
743    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
744    fn from_limit_exceeded(error: LimitExceeded) -> Self {
745        Self::LimitExceeded(error)
746    }
747}
748
749#[cfg_attr(verus_keep_ghost, verus_verify)]
750impl From<MalformedError> for DecodeError {
751    fn from(error: MalformedError) -> Self {
752        Self::from_malformed(error)
753    }
754}
755
756#[cfg_attr(verus_keep_ghost, verus_verify)]
757impl From<LimitExceeded> for DecodeError {
758    fn from(error: LimitExceeded) -> Self {
759        Self::from_limit_exceeded(error)
760    }
761}
762
763#[cfg(verus_keep_ghost)]
764verus! {
765
766impl FromSpecImpl<MalformedError> for DecodeError {
767    open spec fn obeys_from_spec() -> bool {
768        true
769    }
770
771    open spec fn from_spec(error: MalformedError) -> DecodeError {
772        DecodeError::Malformed(error)
773    }
774}
775
776impl FromSpecImpl<LimitExceeded> for DecodeError {
777    open spec fn obeys_from_spec() -> bool {
778        true
779    }
780
781    open spec fn from_spec(error: LimitExceeded) -> DecodeError {
782        DecodeError::LimitExceeded(error)
783    }
784}
785
786}
787
788impl From<io::Error> for DecodeError {
789    fn from(error: io::Error) -> Self {
790        Self::Io(error.kind().into())
791    }
792}
793
794#[cfg(test)]
795mod tests;