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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[non_exhaustive]
11#[cfg_attr(verus_keep_ghost, verus_verify)]
12pub enum IoErrorKind {
13 NotFound,
15 PermissionDenied,
17 ConnectionRefused,
19 ConnectionReset,
21 ConnectionAborted,
23 NotConnected,
25 AddressInUse,
27 AddressNotAvailable,
29 BrokenPipe,
31 AlreadyExists,
33 WouldBlock,
35 InvalidInput,
37 InvalidData,
39 TimedOut,
41 WriteZero,
43 Interrupted,
45 Unsupported,
47 UnexpectedEof,
49 OutOfMemory,
51 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84#[non_exhaustive]
85#[cfg_attr(verus_keep_ghost, verus_verify)]
86pub enum HuffmanErrorKind {
87 ReservedFlags(u8),
89 InvalidBounds {
91 low: i32,
93 high: i32,
95 },
96 InvalidRangeLength(u8),
98 InvalidRangePartition,
100 InvalidLineOrder,
102 InvalidSpecialLine,
104 DuplicateSpecialLine,
106 NoCodes,
108 Oversubscribed,
110 TrailingBits(u64),
112 NonZeroPadding,
114 InvalidCode,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120#[non_exhaustive]
121#[cfg_attr(verus_keep_ghost, verus_verify)]
122pub enum MmrErrorKind {
123 InvalidMode {
125 bit_offset: usize,
127 },
128 ExtensionMode {
130 bit_offset: usize,
132 },
133 InvalidRunCode {
135 bit_offset: usize,
137 black: bool,
139 },
140 RunExceedsRow,
142 InvalidTransition,
144 NonProgress,
146 TooManyModes,
148 MissingEofb,
150 InvalidEofb,
152 TrailingData,
154 NonZeroPadding,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160#[non_exhaustive]
161#[cfg_attr(verus_keep_ghost, verus_verify)]
162pub enum HalftoneErrorKind {
163 InvalidPatternDictionaryFlags(u8),
165 InvalidPatternDimensions {
167 width: u8,
169 height: u8,
171 },
172 InvalidHalftoneFlags(u8),
174 InvalidConfiguration,
176 InvalidBitmapDimensions {
178 expected_width: u32,
180 expected_height: u32,
182 actual_width: u32,
184 actual_height: u32,
186 },
187 InvalidGrayBitDepth(u8),
189 EmptyPatternDictionary,
191 InconsistentPatternDimensions,
193 InvalidPatternIndex {
195 index: u32,
197 pattern_count: u64,
199 },
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204#[non_exhaustive]
205#[cfg_attr(verus_keep_ghost, verus_verify)]
206pub enum GenericRegionErrorKind {
207 ReservedFlags(u8),
209 InvalidFlags(u8),
211 InvalidAdaptivePixel {
213 number: u8,
215 x: i32,
217 y: i32,
219 },
220 InvalidSkipDimensions,
222 InvalidArithmeticTerminator,
224 UnexpectedArithmeticMarker {
226 offset: usize,
228 code: u8,
230 },
231 RowCountMismatch {
233 expected: u32,
235 actual: u32,
237 },
238 ContextIndex {
240 index: usize,
242 count: usize,
244 },
245}
246
247#[derive(Debug, PartialEq, Eq)]
249#[non_exhaustive]
250#[cfg_attr(verus_keep_ghost, verus_verify)]
251pub enum MalformedError {
252 UnexpectedEof {
254 offset: u64,
256 needed: u64,
258 remaining: u64,
260 },
261 InvalidFileSignature,
263 ReservedFileHeaderFlags(u8),
265 InvalidBitCount(u8),
267 ReservedSegmentType(u8),
269 InvalidReferredToCountCode(u8),
271 NonCanonicalReferredToCount(u32),
273 NonZeroUnusedRetentionFlags,
275 InvalidReferredSegmentNumber {
277 segment: u32,
279 referred: u32,
281 },
282 InvalidExtensionType(u32),
284 InvalidCommentExtension,
286 InvalidProfilesSegment(u32),
288 InvalidHuffman(HuffmanErrorKind),
290 InvalidArithmeticContextState {
292 state_index: u8,
294 mps: u8,
296 },
297 InsufficientArithmeticContexts {
299 required: usize,
301 actual: usize,
303 },
304 InvalidIaidCodeLength(u8),
306 InvalidMmr(MmrErrorKind),
308 InvalidSymbolText(&'static str),
310 SymbolIdOutOfRange {
312 id: u32,
314 available: u32,
316 },
317 InvalidSymbolDimensions,
319 InvalidHalftone(HalftoneErrorKind),
321 InvalidGenericRegion(GenericRegionErrorKind),
323 InvalidPageState(&'static str),
325 InvalidUnknownSegmentLength(u8),
327 InvalidSegmentDataLength {
329 segment_type: u8,
331 expected: u64,
333 actual: u64,
335 },
336 ReservedRegionFlags(u8),
338 InvalidCombinationOperator(u8),
340 UnknownHeightWithoutStriping,
342 InvalidStripeEndRow(u32),
344 DuplicateSegmentNumber(u32),
346 NonIncreasingSegmentNumber {
348 previous: u32,
350 current: u32,
352 },
353 MissingReferredSegment {
355 segment: u32,
357 referred: u32,
359 },
360 InvalidPageAssociation {
362 segment: u32,
364 page: u32,
366 },
367 MissingPageInformation(u32),
369 DuplicatePageBoundary {
371 page: u32,
373 segment_type: u8,
375 },
376 SegmentAfterEndOfPage {
378 segment: u32,
380 page: u32,
382 },
383 MissingEndOfPage(u32),
385 MissingEndOfFile,
387 TrailingData(u64),
389 PageCountMismatch {
391 declared: u32,
393 actual: u32,
395 },
396 InvalidSegmentReferences(u32),
398 MissingGenericRegionTerminator,
400 GenericRegionRowCount {
402 declared: u32,
404 actual: u32,
406 },
407 InvalidRetentionFlags {
409 segment: u32,
411 referred: u32,
413 },
414 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
596#[non_exhaustive]
597#[cfg_attr(verus_keep_ghost, verus_verify)]
598pub enum UnsupportedFeature {
599 Colour,
601 SegmentType(u8),
603 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626#[non_exhaustive]
627#[cfg_attr(verus_keep_ghost, verus_verify)]
628pub enum LimitKind {
629 Width,
631 Height,
633 PagePixels,
635 Memory,
637 StreamBytes,
639 Pages,
641 Segments,
643 Symbols,
645 ReferencesPerSegment,
647 TotalReferences,
649 ReferenceDepth,
651 NestingDepth,
653 Work,
655 DecodedBitmapBytes,
657 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
669#[cfg_attr(verus_keep_ghost, verus_verify)]
670pub struct LimitExceeded {
671 pub kind: LimitKind,
673 pub limit: u64,
675 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#[derive(Debug)]
691#[non_exhaustive]
692#[cfg_attr(verus_keep_ghost, verus_verify)]
693pub enum DecodeError {
694 Malformed(MalformedError),
696 Unsupported(UnsupportedFeature),
698 LimitExceeded(LimitExceeded),
700 Allocation {
702 requested_bytes: u64,
704 },
705 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;