Skip to main content

structured_zstd/decoding/
errors.rs

1//! Errors that might occur while decoding zstd formatted data
2
3use crate::bit_io::GetBitsError;
4use crate::blocks::block::BlockType;
5use crate::blocks::literals_section::LiteralsSectionType;
6use crate::io::Error;
7use alloc::vec::Vec;
8use core::fmt;
9#[cfg(feature = "std")]
10use std::error::Error as StdError;
11
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum FrameDescriptorError {
15    InvalidFrameContentSizeFlag {
16        got: u8,
17    },
18    /// The descriptor's `Reserved_bit` (bit 3) is set, which a decoder of this
19    /// format version must refuse.
20    ReservedBitSet,
21}
22
23impl fmt::Display for FrameDescriptorError {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match self {
26            Self::InvalidFrameContentSizeFlag { got } => write!(
27                f,
28                "Invalid Frame_Content_Size_Flag; Is: {got}, Should be one of: 0, 1, 2, 3"
29            ),
30            Self::ReservedBitSet => write!(
31                f,
32                "Reserved_bit of the Frame_Header_Descriptor is set; it must be zero"
33            ),
34        }
35    }
36}
37
38#[cfg(feature = "std")]
39impl StdError for FrameDescriptorError {}
40
41#[derive(Debug)]
42#[non_exhaustive]
43pub enum FrameHeaderError {
44    WindowTooBig { got: u64 },
45    WindowTooSmall { got: u64 },
46    FrameDescriptorError(FrameDescriptorError),
47    DictIdTooSmall { got: usize, expected: usize },
48    MismatchedFrameSize { got: usize, expected: u8 },
49    FrameSizeIsZero,
50    InvalidFrameSize { got: u8 },
51}
52
53impl fmt::Display for FrameHeaderError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::WindowTooBig { got } => write!(
57                f,
58                "window_size bigger than allowed maximum. Is: {}, Should be lower than: {}",
59                got,
60                crate::common::MAX_WINDOW_SIZE
61            ),
62            Self::WindowTooSmall { got } => write!(
63                f,
64                "window_size smaller than allowed minimum. Is: {}, Should be greater than: {}",
65                got,
66                crate::common::MIN_WINDOW_SIZE
67            ),
68            Self::FrameDescriptorError(e) => write!(f, "{e:?}"),
69            Self::DictIdTooSmall { got, expected } => write!(
70                f,
71                "Not enough bytes in dict_id. Is: {got}, Should be: {expected}"
72            ),
73            Self::MismatchedFrameSize { got, expected } => write!(
74                f,
75                "frame_content_size does not have the right length. Is: {got}, Should be: {expected}"
76            ),
77            Self::FrameSizeIsZero => write!(f, "frame_content_size was zero"),
78            Self::InvalidFrameSize { got } => write!(
79                f,
80                "Invalid frame_content_size. Is: {got}, Should be one of 1, 2, 4, 8 bytes"
81            ),
82        }
83    }
84}
85
86#[cfg(feature = "std")]
87impl StdError for FrameHeaderError {
88    fn source(&self) -> Option<&(dyn StdError + 'static)> {
89        match self {
90            FrameHeaderError::FrameDescriptorError(source) => Some(source),
91            _ => None,
92        }
93    }
94}
95
96impl From<FrameDescriptorError> for FrameHeaderError {
97    fn from(error: FrameDescriptorError) -> Self {
98        Self::FrameDescriptorError(error)
99    }
100}
101
102#[derive(Debug)]
103#[non_exhaustive]
104pub enum ReadFrameHeaderError {
105    MagicNumberReadError(Error),
106    BadMagicNumber(u32),
107    FrameDescriptorReadError(Error),
108    InvalidFrameDescriptor(FrameDescriptorError),
109    WindowDescriptorReadError(Error),
110    DictionaryIdReadError(Error),
111    FrameContentSizeReadError(Error),
112    SkipFrame { magic_number: u32, length: u32 },
113}
114
115impl fmt::Display for ReadFrameHeaderError {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            Self::MagicNumberReadError(e) => write!(f, "Error while reading magic number: {e}"),
119            Self::BadMagicNumber(e) => write!(f, "Read wrong magic number: 0x{e:X}"),
120            Self::FrameDescriptorReadError(e) => {
121                write!(f, "Error while reading frame descriptor: {e}")
122            }
123            Self::InvalidFrameDescriptor(e) => write!(f, "{e:?}"),
124            Self::WindowDescriptorReadError(e) => {
125                write!(f, "Error while reading window descriptor: {e}")
126            }
127            Self::DictionaryIdReadError(e) => write!(f, "Error while reading dictionary id: {e}"),
128            Self::FrameContentSizeReadError(e) => {
129                write!(f, "Error while reading frame content size: {e}")
130            }
131            Self::SkipFrame {
132                magic_number,
133                length,
134            } => write!(
135                f,
136                "SkippableFrame encountered with MagicNumber 0x{magic_number:X} and length {length} bytes"
137            ),
138        }
139    }
140}
141
142#[cfg(feature = "std")]
143impl StdError for ReadFrameHeaderError {
144    fn source(&self) -> Option<&(dyn StdError + 'static)> {
145        match self {
146            ReadFrameHeaderError::MagicNumberReadError(source) => Some(source),
147            ReadFrameHeaderError::FrameDescriptorReadError(source) => Some(source),
148            ReadFrameHeaderError::InvalidFrameDescriptor(source) => Some(source),
149            ReadFrameHeaderError::WindowDescriptorReadError(source) => Some(source),
150            ReadFrameHeaderError::DictionaryIdReadError(source) => Some(source),
151            ReadFrameHeaderError::FrameContentSizeReadError(source) => Some(source),
152            _ => None,
153        }
154    }
155}
156
157impl From<FrameDescriptorError> for ReadFrameHeaderError {
158    fn from(error: FrameDescriptorError) -> Self {
159        Self::InvalidFrameDescriptor(error)
160    }
161}
162
163#[derive(Debug)]
164#[non_exhaustive]
165pub enum BlockHeaderReadError {
166    ReadError(Error),
167    FoundReservedBlock,
168    BlockTypeError(BlockTypeError),
169    BlockSizeError(BlockSizeError),
170}
171
172#[cfg(feature = "std")]
173impl std::error::Error for BlockHeaderReadError {
174    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
175        match self {
176            BlockHeaderReadError::ReadError(source) => Some(source),
177            BlockHeaderReadError::BlockTypeError(source) => Some(source),
178            BlockHeaderReadError::BlockSizeError(source) => Some(source),
179            BlockHeaderReadError::FoundReservedBlock => None,
180        }
181    }
182}
183
184impl ::core::fmt::Display for BlockHeaderReadError {
185    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
186        match self {
187            BlockHeaderReadError::ReadError(_) => write!(f, "Error while reading the block header"),
188            BlockHeaderReadError::FoundReservedBlock => write!(
189                f,
190                "Reserved block occured. This is considered corruption by the documentation"
191            ),
192            BlockHeaderReadError::BlockTypeError(e) => write!(f, "Error getting block type: {e}"),
193            BlockHeaderReadError::BlockSizeError(e) => {
194                write!(f, "Error getting block content size: {e}")
195            }
196        }
197    }
198}
199
200impl From<Error> for BlockHeaderReadError {
201    fn from(val: Error) -> Self {
202        Self::ReadError(val)
203    }
204}
205
206impl From<BlockTypeError> for BlockHeaderReadError {
207    fn from(val: BlockTypeError) -> Self {
208        Self::BlockTypeError(val)
209    }
210}
211
212impl From<BlockSizeError> for BlockHeaderReadError {
213    fn from(val: BlockSizeError) -> Self {
214        Self::BlockSizeError(val)
215    }
216}
217
218#[derive(Debug)]
219#[non_exhaustive]
220pub enum BlockTypeError {
221    InvalidBlocktypeNumber { num: u8 },
222}
223
224#[cfg(feature = "std")]
225impl std::error::Error for BlockTypeError {}
226
227impl core::fmt::Display for BlockTypeError {
228    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
229        match self {
230            BlockTypeError::InvalidBlocktypeNumber { num } => {
231                write!(
232                    f,
233                    "Invalid Blocktype number. Is: {num}. Should be one of: 0, 1, 2, 3 (3 is reserved).",
234                )
235            }
236        }
237    }
238}
239
240#[derive(Debug)]
241#[non_exhaustive]
242pub enum BlockSizeError {
243    BlockSizeTooLarge { size: u32 },
244}
245
246#[cfg(feature = "std")]
247impl std::error::Error for BlockSizeError {}
248
249impl core::fmt::Display for BlockSizeError {
250    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251        match self {
252            BlockSizeError::BlockSizeTooLarge { size } => {
253                write!(
254                    f,
255                    "Blocksize was bigger than the absolute maximum {} (128kb). Is: {}",
256                    crate::common::MAX_BLOCK_SIZE,
257                    size,
258                )
259            }
260        }
261    }
262}
263
264#[derive(Debug)]
265#[non_exhaustive]
266pub enum DecompressBlockError {
267    BlockContentReadError(Error),
268    MalformedSectionHeader {
269        expected_len: usize,
270        remaining_bytes: usize,
271    },
272    DecompressLiteralsError(DecompressLiteralsError),
273    LiteralsSectionParseError(LiteralsSectionParseError),
274    SequencesHeaderParseError(SequencesHeaderParseError),
275    DecodeSequenceError(DecodeSequenceError),
276    ExecuteSequencesError(ExecuteSequencesError),
277    /// The block's literals, or its whole output, run past the block maximum
278    /// (RFC 8878 3.1.1.2.4, `Block_Maximum_Size`): `size` bytes where
279    /// `maximum` is the most a block of this frame may produce, the smaller of
280    /// its window and 128 KiB.
281    ExpandsPastBlockMaximum {
282        size: usize,
283        maximum: usize,
284    },
285    /// A block with no sequences whose literals do not fit a fixed-capacity
286    /// backend: `requested` bytes at `tail` against `capacity`. The block is
287    /// within the block maximum, so this says the caller's slice is short, and
288    /// the frame decoder turns it into `TargetTooSmall` (or a content-size
289    /// mismatch for a frame that declared one). Growable backends grow instead
290    /// and never produce it.
291    LiteralsOutputOverflow {
292        tail: usize,
293        requested: usize,
294        capacity: usize,
295    },
296}
297
298#[cfg(feature = "std")]
299impl std::error::Error for DecompressBlockError {
300    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
301        match self {
302            DecompressBlockError::BlockContentReadError(source) => Some(source),
303            DecompressBlockError::DecompressLiteralsError(source) => Some(source),
304            DecompressBlockError::LiteralsSectionParseError(source) => Some(source),
305            DecompressBlockError::SequencesHeaderParseError(source) => Some(source),
306            DecompressBlockError::DecodeSequenceError(source) => Some(source),
307            DecompressBlockError::ExecuteSequencesError(source) => Some(source),
308            _ => None,
309        }
310    }
311}
312
313impl core::fmt::Display for DecompressBlockError {
314    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
315        match self {
316            DecompressBlockError::BlockContentReadError(e) => {
317                write!(f, "Error while reading the block content: {e}")
318            }
319            DecompressBlockError::MalformedSectionHeader {
320                expected_len,
321                remaining_bytes,
322            } => {
323                write!(
324                    f,
325                    "Malformed section header. Says literals would be this long: {expected_len} but there are only {remaining_bytes} bytes left",
326                )
327            }
328            DecompressBlockError::DecompressLiteralsError(e) => write!(f, "{e:?}"),
329            DecompressBlockError::LiteralsSectionParseError(e) => write!(f, "{e:?}"),
330            DecompressBlockError::SequencesHeaderParseError(e) => write!(f, "{e:?}"),
331            DecompressBlockError::DecodeSequenceError(e) => write!(f, "{e:?}"),
332            DecompressBlockError::ExecuteSequencesError(e) => write!(f, "{e:?}"),
333            DecompressBlockError::ExpandsPastBlockMaximum { size, maximum } => write!(
334                f,
335                "Block expands to {size} bytes, past this frame's maximum of {maximum}"
336            ),
337            DecompressBlockError::LiteralsOutputOverflow {
338                tail,
339                requested,
340                capacity,
341            } => write!(
342                f,
343                "Literals would write past the output buffer: tail={tail}, requested={requested}, capacity={capacity}"
344            ),
345        }
346    }
347}
348
349impl From<Error> for DecompressBlockError {
350    fn from(val: Error) -> Self {
351        Self::BlockContentReadError(val)
352    }
353}
354
355impl From<DecompressLiteralsError> for DecompressBlockError {
356    fn from(val: DecompressLiteralsError) -> Self {
357        Self::DecompressLiteralsError(val)
358    }
359}
360
361impl From<LiteralsSectionParseError> for DecompressBlockError {
362    fn from(val: LiteralsSectionParseError) -> Self {
363        Self::LiteralsSectionParseError(val)
364    }
365}
366
367impl From<SequencesHeaderParseError> for DecompressBlockError {
368    fn from(val: SequencesHeaderParseError) -> Self {
369        Self::SequencesHeaderParseError(val)
370    }
371}
372
373impl From<DecodeSequenceError> for DecompressBlockError {
374    fn from(val: DecodeSequenceError) -> Self {
375        Self::DecodeSequenceError(val)
376    }
377}
378
379impl From<ExecuteSequencesError> for DecompressBlockError {
380    fn from(val: ExecuteSequencesError) -> Self {
381        Self::ExecuteSequencesError(val)
382    }
383}
384
385#[derive(Debug)]
386#[non_exhaustive]
387pub enum DecodeBlockContentError {
388    DecoderStateIsFailed,
389    ExpectedHeaderOfPreviousBlock,
390    ReadError {
391        step: BlockType,
392        source: Error,
393    },
394    DecompressBlockError(DecompressBlockError),
395    /// The block's decompressed payload would not fit in the
396    /// caller-provided output buffer (only reachable via the
397    /// direct-decode path with a fixed-capacity backend). Internal
398    /// diagnostic variant — the frame-level decoder always
399    /// converts this into
400    /// `FrameDecoderError::FrameContentSizeMismatch` before
401    /// returning to the user, so external callers never observe
402    /// it. The `step: BlockType` field is kept for in-crate
403    /// debugging (which decode arm triggered the overshoot) but is
404    /// not part of any caller-visible distinction.
405    BackendOverflow {
406        step: BlockType,
407    },
408}
409
410#[cfg(feature = "std")]
411impl std::error::Error for DecodeBlockContentError {
412    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
413        match self {
414            DecodeBlockContentError::ReadError { step: _, source } => Some(source),
415            DecodeBlockContentError::DecompressBlockError(source) => Some(source),
416            _ => None,
417        }
418    }
419}
420
421impl core::fmt::Display for DecodeBlockContentError {
422    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
423        match self {
424            DecodeBlockContentError::DecoderStateIsFailed => {
425                write!(
426                    f,
427                    "Can't decode next block if failed along the way. Results will be nonsense",
428                )
429            }
430            DecodeBlockContentError::ExpectedHeaderOfPreviousBlock => {
431                write!(
432                    f,
433                    "Can't decode next block body, while expecting to decode the header of the previous block. Results will be nonsense",
434                )
435            }
436            DecodeBlockContentError::ReadError { step, source } => {
437                write!(f, "Error while reading bytes for {step}: {source}",)
438            }
439            DecodeBlockContentError::DecompressBlockError(e) => write!(f, "{e:?}"),
440            DecodeBlockContentError::BackendOverflow { step } => write!(
441                f,
442                "{step} block's decompressed payload exceeds the caller-provided output buffer",
443            ),
444        }
445    }
446}
447
448impl From<DecompressBlockError> for DecodeBlockContentError {
449    fn from(val: DecompressBlockError) -> Self {
450        Self::DecompressBlockError(val)
451    }
452}
453
454#[derive(Debug)]
455#[non_exhaustive]
456pub enum DecodeBufferError {
457    NotEnoughBytesInDictionary {
458        got: usize,
459        need: usize,
460    },
461    OffsetTooBig {
462        offset: usize,
463        buf_len: usize,
464    },
465    ZeroOffset,
466    /// Legacy unit variant kept for binary compatibility with earlier
467    /// snapshots of this enum. Not surfaced from any current
468    /// production path — `BufferBackend::try_extend` /
469    /// `try_extend_from_within` and the new `try_reserve` (used by
470    /// `DecodeBuffer::repeat`) carry their failures through the
471    /// richer [`Self::OutputBufferOverflow`] variant below, which
472    /// reports the offending `tail` / `requested` / `capacity`
473    /// triple. New code should pattern-match on
474    /// `OutputBufferOverflow`; this unit variant is retained to keep
475    /// the `#[non_exhaustive]` enum's existing discriminant set
476    /// stable.
477    BackendOverflow,
478    /// Repeat-side match copy would write past the writable tail of
479    /// a fixed-capacity backend (`UserSliceBackend`). Surfaced by
480    /// `DecodeBuffer::repeat` / `_lookahead`
481    /// when the new `BufferBackend::try_reserve` rejects the
482    /// pre-write capacity check — keeping the safe public decode
483    /// APIs error-returning instead of panicking via the per-call
484    /// `assert!` inside `extend_from_within_unchecked`. Growable
485    /// backends (`FlatBuf`, `RingBuffer`) never produce this; their
486    /// `try_reserve` falls through to infallible `reserve`.
487    OutputBufferOverflow {
488        tail: usize,
489        requested: usize,
490        capacity: usize,
491    },
492}
493
494#[cfg(feature = "std")]
495impl std::error::Error for DecodeBufferError {}
496
497impl core::fmt::Display for DecodeBufferError {
498    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
499        match self {
500            DecodeBufferError::NotEnoughBytesInDictionary { got, need } => {
501                write!(
502                    f,
503                    "Need {need} bytes from the dictionary but it is only {got} bytes long",
504                )
505            }
506            DecodeBufferError::OffsetTooBig { offset, buf_len } => {
507                write!(f, "offset: {offset} bigger than buffer: {buf_len}",)
508            }
509            DecodeBufferError::ZeroOffset => {
510                write!(f, "Illegal offset: 0 found")
511            }
512            DecodeBufferError::BackendOverflow => {
513                write!(
514                    f,
515                    "Match repeat would overflow the output buffer's fixed capacity"
516                )
517            }
518            DecodeBufferError::OutputBufferOverflow {
519                tail,
520                requested,
521                capacity,
522            } => {
523                write!(
524                    f,
525                    "Match repeat would write past fixed-capacity buffer: tail={tail}, requested={requested}, capacity={capacity}"
526                )
527            }
528        }
529    }
530}
531
532#[derive(Debug)]
533#[non_exhaustive]
534pub enum DictionaryDecodeError {
535    BadMagicNum { got: [u8; 4] },
536    DictionaryTooSmall { got: usize, need: usize },
537    ZeroDictionaryId,
538    ZeroRepeatOffsetInDictionary { index: u8 },
539    FSETableError(FSETableError),
540    HuffmanTableError(HuffmanTableError),
541}
542
543#[cfg(feature = "std")]
544impl std::error::Error for DictionaryDecodeError {
545    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
546        match self {
547            DictionaryDecodeError::FSETableError(source) => Some(source),
548            DictionaryDecodeError::HuffmanTableError(source) => Some(source),
549            _ => None,
550        }
551    }
552}
553
554impl core::fmt::Display for DictionaryDecodeError {
555    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
556        match self {
557            DictionaryDecodeError::BadMagicNum { got } => {
558                write!(
559                    f,
560                    "Bad magic_num at start of the dictionary; Got: {:#04X?}, Expected: {:#04x?}",
561                    got,
562                    crate::decoding::dictionary::MAGIC_NUM,
563                )
564            }
565            DictionaryDecodeError::DictionaryTooSmall { got, need } => {
566                write!(
567                    f,
568                    "Dictionary is too small: got {got} bytes, need at least {need} bytes",
569                )
570            }
571            DictionaryDecodeError::ZeroDictionaryId => {
572                write!(f, "Dictionary id must be non-zero")
573            }
574            DictionaryDecodeError::ZeroRepeatOffsetInDictionary { index } => {
575                write!(f, "Dictionary repeat offset rep{index} must be non-zero")
576            }
577            DictionaryDecodeError::FSETableError(e) => write!(f, "{e:?}"),
578            DictionaryDecodeError::HuffmanTableError(e) => write!(f, "{e:?}"),
579        }
580    }
581}
582
583impl From<FSETableError> for DictionaryDecodeError {
584    fn from(val: FSETableError) -> Self {
585        Self::FSETableError(val)
586    }
587}
588
589impl From<HuffmanTableError> for DictionaryDecodeError {
590    fn from(val: HuffmanTableError) -> Self {
591        Self::HuffmanTableError(val)
592    }
593}
594
595#[derive(Debug)]
596#[non_exhaustive]
597pub enum FrameDecoderError {
598    ReadFrameHeaderError(ReadFrameHeaderError),
599    FrameHeaderError(FrameHeaderError),
600    WindowSizeTooBig {
601        requested: u64,
602    },
603    DictionaryDecodeError(DictionaryDecodeError),
604    FailedToReadBlockHeader(BlockHeaderReadError),
605    FailedToReadBlockBody(DecodeBlockContentError),
606    FailedToReadChecksum(Error),
607    NotYetInitialized,
608    FailedToInitialize(FrameHeaderError),
609    FailedToDrainDecodebuffer(Error),
610    FailedToSkipFrame,
611    TargetTooSmall,
612    /// Decoded block sizes don't sum to the frame's declared
613    /// `frame_content_size` (either a block claims to expand past
614    /// FCS, or the stream ends before reaching FCS). Indicates a
615    /// malformed or corrupt frame — distinct from
616    /// [`Self::TargetTooSmall`] (which is the caller's
617    /// responsibility) so callers can tell decoder-side issues
618    /// apart from their own buffer sizing mistakes.
619    FrameContentSizeMismatch {
620        declared: u64,
621        produced: u64,
622    },
623    /// The frame carried a trailing XXH64 content checksum and the decoder
624    /// was set to [`ContentChecksum::Verify`](crate::decoding::ContentChecksum::Verify),
625    /// but the digest computed over the decompressed output did not match the
626    /// stored value. Indicates corruption in the compressed stream or its
627    /// trailing checksum. `expected` is the value read from the frame tail;
628    /// `calculated` is the digest the decoder computed (both low 32 bits).
629    ChecksumMismatch {
630        expected: u32,
631        calculated: u32,
632    },
633    DictNotProvided {
634        dict_id: u32,
635    },
636    DictIdMismatch {
637        expected: u32,
638        provided: u32,
639    },
640    DictAlreadyRegistered {
641        dict_id: u32,
642    },
643    /// Frame header's `dict_id` did not match the value pinned via
644    /// `FrameDecoder::expect_dict_id`. Returned BEFORE any block
645    /// decode and BEFORE any output is produced — no XXH64 init,
646    /// no partial output. Scratch buffer allocation / reservation
647    /// for the decode pipeline happens during frame-header parsing,
648    /// which is already complete when this validation fires, so
649    /// the cost of scratch sizing is paid even on a mismatched
650    /// header. `expected` is the pinned value (`Some(0)` is
651    /// treated as "no dictionary expected", matching a frame whose
652    /// header omits the optional `Dictionary_ID` field); `found`
653    /// reports what the frame actually carried (`None` when the
654    /// header omits the field, `Some(id)` when it does not).
655    #[cfg(feature = "lsm")]
656    UnexpectedDictId {
657        expected: Option<u32>,
658        found: Option<u32>,
659    },
660    /// Frame header's raw `Window_Descriptor` byte did not match
661    /// the value pinned via `FrameDecoder::expect_window_descriptor`.
662    /// Returned BEFORE any block decode work. Single-segment frames
663    /// (which omit the `Window_Descriptor` byte from the wire) are
664    /// reported via `found: None` so callers can distinguish
665    /// "wrong descriptor" from "no descriptor on the wire".
666    #[cfg(feature = "lsm")]
667    UnexpectedWindowDescriptor {
668        expected: u8,
669        found: Option<u8>,
670    },
671    /// Block-precise variant of [`Self::FailedToReadBlockHeader`]: a block
672    /// header read failed and the decoder captured WHERE. `block_index` is
673    /// the 0-based index of the failing block in the frame; `frame_offset`
674    /// is the frame-absolute byte offset of that block's `Block_Header`
675    /// (matches `FrameEmitInfo.blocks[block_index].offset_in_frame` from the
676    /// encode side). Lets per-block recovery (ECC repair) target the one bad
677    /// block instead of re-fetching the whole frame.
678    #[cfg(feature = "lsm")]
679    FailedToReadBlockHeaderAt {
680        source: BlockHeaderReadError,
681        block_index: u32,
682        frame_offset: u32,
683    },
684    /// Block-precise variant of [`Self::FailedToReadBlockBody`]: a block
685    /// body decode failed. Carries the same `block_index` / `frame_offset`
686    /// coordinates plus the failing block's structural metadata
687    /// ([`FrameBlock`]) reconstructed from its header, so a consumer can
688    /// locate and repair exactly this block.
689    ///
690    /// [`FrameBlock`]: crate::encoding::frame_emit_info::FrameBlock
691    #[cfg(feature = "lsm")]
692    FailedToReadBlockBodyAt {
693        source: DecodeBlockContentError,
694        block_index: u32,
695        frame_offset: u32,
696        block: crate::encoding::frame_emit_info::FrameBlock,
697    },
698    /// `FrameDecoder::decode_blocks_partial` was called with
699    /// `start_block > end_block` (the half-open block range is
700    /// empty-or-inverted and cannot describe a valid subset). API
701    /// misuse, surfaced as `Err` rather than a `PartialDecode`
702    /// outcome — distinct from a corrupt-frame stop, which is
703    /// reported via `PartialDecode::stopped_at`.
704    #[cfg(feature = "lsm")]
705    InvalidBlockRange {
706        start_block: u32,
707        end_block: u32,
708    },
709    /// A resuming [`FrameDecoder::decode_blocks_partial`] was given a
710    /// `window_prime` (via [`ResumeInput`]) shorter than the match window the
711    /// resume block can reach back into. The resumed decode would read past the
712    /// primed history and silently mis-resolve matches, so it is rejected up
713    /// front. `got` is the supplied prime length; `need` is the required
714    /// minimum (`min(window_size, output_offset)`).
715    ///
716    /// [`FrameDecoder::decode_blocks_partial`]: crate::decoding::FrameDecoder::decode_blocks_partial
717    /// [`ResumeInput`]: crate::decoding::ResumeInput
718    #[cfg(feature = "lsm")]
719    ResumeWindowTooShort {
720        got: usize,
721        need: usize,
722    },
723    /// A resuming [`FrameDecoder::decode_blocks_partial`] was given a
724    /// [`ResumeInput`] whose [`ResumeState`] was captured from a frame with a
725    /// different decode-relevant shape (window size, dictionary id,
726    /// single-segment flag, content-checksum flag, or magicless mode) than the
727    /// frame currently [`reset`](crate::decoding::FrameDecoder::reset) into the
728    /// decoder. Applying entropy/repcode state across mismatched frames would
729    /// yield byte-wrong output, so it is rejected up front.
730    ///
731    /// [`FrameDecoder::decode_blocks_partial`]: crate::decoding::FrameDecoder::decode_blocks_partial
732    /// [`ResumeInput`]: crate::decoding::ResumeInput
733    /// [`ResumeState`]: crate::decoding::ResumeState
734    #[cfg(feature = "lsm")]
735    ResumeFrameMismatch,
736    /// A resume was attempted while a dictionary that carries no ID was
737    /// applied, on either the emitting or the resuming side.
738    ///
739    /// The frame key tells dictionaries apart by the ID the decoder recorded,
740    /// and a raw-content dictionary has none — every one of them is ID 0. Two
741    /// different raw dictionaries therefore key alike, so a snapshot captured
742    /// under one would be restored under the other: foreign entropy and repcode
743    /// state, and output that is wrong with nothing to say so. A dictionary that
744    /// cannot be told from another cannot carry a resume across, so it is
745    /// refused. Give the dictionary an ID (a serialized dictionary carries one,
746    /// or supply a non-zero one to
747    /// [`Dictionary::from_raw_content`](crate::decoding::Dictionary::from_raw_content))
748    /// to make it resumable.
749    #[cfg(feature = "lsm")]
750    ResumeUnidentifiedDictionary,
751}
752
753#[cfg(feature = "std")]
754impl StdError for FrameDecoderError {
755    fn source(&self) -> Option<&(dyn StdError + 'static)> {
756        match self {
757            FrameDecoderError::ReadFrameHeaderError(source) => Some(source),
758            FrameDecoderError::FrameHeaderError(source) => Some(source),
759            FrameDecoderError::DictionaryDecodeError(source) => Some(source),
760            FrameDecoderError::FailedToReadBlockHeader(source) => Some(source),
761            FrameDecoderError::FailedToReadBlockBody(source) => Some(source),
762            #[cfg(feature = "lsm")]
763            FrameDecoderError::FailedToReadBlockHeaderAt { source, .. } => Some(source),
764            #[cfg(feature = "lsm")]
765            FrameDecoderError::FailedToReadBlockBodyAt { source, .. } => Some(source),
766            FrameDecoderError::FailedToReadChecksum(source) => Some(source),
767            FrameDecoderError::FailedToInitialize(source) => Some(source),
768            FrameDecoderError::FailedToDrainDecodebuffer(source) => Some(source),
769            _ => None,
770        }
771    }
772}
773
774impl core::fmt::Display for FrameDecoderError {
775    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
776        match self {
777            FrameDecoderError::ReadFrameHeaderError(e) => {
778                write!(f, "{e:?}")
779            }
780            FrameDecoderError::FrameHeaderError(e) => {
781                write!(f, "{e:?}")
782            }
783            FrameDecoderError::WindowSizeTooBig { requested } => {
784                write!(
785                    f,
786                    "Specified window_size is too big; Requested: {}, Allowed: {}",
787                    requested,
788                    crate::common::MAXIMUM_ALLOWED_WINDOW_SIZE,
789                )
790            }
791            FrameDecoderError::DictionaryDecodeError(e) => {
792                write!(f, "{e:?}")
793            }
794            FrameDecoderError::FailedToReadBlockHeader(e) => {
795                write!(f, "Failed to parse/decode block body: {e}")
796            }
797            FrameDecoderError::FailedToReadBlockBody(e) => {
798                write!(f, "Failed to parse block header: {e}")
799            }
800            #[cfg(feature = "lsm")]
801            FrameDecoderError::FailedToReadBlockHeaderAt {
802                source,
803                block_index,
804                frame_offset,
805            } => {
806                write!(
807                    f,
808                    "Failed to read block header at block {block_index} (frame offset {frame_offset}): {source}"
809                )
810            }
811            #[cfg(feature = "lsm")]
812            FrameDecoderError::FailedToReadBlockBodyAt {
813                source,
814                block_index,
815                frame_offset,
816                ..
817            } => {
818                write!(
819                    f,
820                    "Failed to decode block body at block {block_index} (frame offset {frame_offset}): {source}"
821                )
822            }
823            FrameDecoderError::FailedToReadChecksum(e) => {
824                write!(f, "Failed to read checksum: {e}")
825            }
826            FrameDecoderError::NotYetInitialized => {
827                write!(f, "Decoder must initialized or reset before using it",)
828            }
829            FrameDecoderError::FailedToInitialize(e) => {
830                write!(f, "Decoder encountered error while initializing: {e}")
831            }
832            FrameDecoderError::FailedToDrainDecodebuffer(e) => {
833                write!(
834                    f,
835                    "Decoder encountered error while draining the decodebuffer: {e}",
836                )
837            }
838            FrameDecoderError::FailedToSkipFrame => {
839                write!(
840                    f,
841                    "Failed to skip bytes for the length given in the frame header"
842                )
843            }
844            FrameDecoderError::TargetTooSmall => {
845                write!(
846                    f,
847                    "Target must have at least as many bytes as the content size reported by the frame"
848                )
849            }
850            FrameDecoderError::FrameContentSizeMismatch { declared, produced } => {
851                write!(
852                    f,
853                    "Frame content size mismatch (corrupt frame): declared {declared} bytes, blocks summed to {produced} bytes"
854                )
855            }
856            FrameDecoderError::ChecksumMismatch {
857                expected,
858                calculated,
859            } => {
860                write!(
861                    f,
862                    "Content checksum mismatch (corrupt frame): frame stored 0x{expected:08X}, decoder calculated 0x{calculated:08X}"
863                )
864            }
865            FrameDecoderError::DictNotProvided { dict_id } => {
866                write!(
867                    f,
868                    "Frame header specified dictionary id 0x{dict_id:X} that wasn't provided via add_dict()/add_dict_from_bytes() (or add_dict_handle() on atomic targets) or reset_with_dict_handle()/decode_all_with_dict_handle()/decode_all_with_dict_bytes()"
869                )
870            }
871            FrameDecoderError::DictIdMismatch { expected, provided } => {
872                write!(
873                    f,
874                    "Frame header dictionary id 0x{expected:X} does not match provided dictionary id 0x{provided:X}"
875                )
876            }
877            FrameDecoderError::DictAlreadyRegistered { dict_id } => {
878                write!(
879                    f,
880                    "Dictionary id 0x{dict_id:X} already registered in decoder"
881                )
882            }
883            #[cfg(feature = "lsm")]
884            FrameDecoderError::UnexpectedDictId { expected, found } => {
885                write!(f, "Frame header dict_id mismatch: expected ")?;
886                match expected {
887                    Some(id) => write!(f, "0x{id:X}")?,
888                    None => write!(f, "<none>")?,
889                }
890                write!(f, ", found ")?;
891                match found {
892                    Some(id) => write!(f, "0x{id:X}"),
893                    None => write!(f, "<none>"),
894                }
895            }
896            #[cfg(feature = "lsm")]
897            FrameDecoderError::UnexpectedWindowDescriptor { expected, found } => {
898                write!(
899                    f,
900                    "Frame header window_descriptor mismatch: expected 0x{expected:02X}, found "
901                )?;
902                match found {
903                    Some(byte) => write!(f, "0x{byte:02X}"),
904                    None => write!(f, "<none> (single-segment frame omits window_descriptor)"),
905                }
906            }
907            #[cfg(feature = "lsm")]
908            FrameDecoderError::InvalidBlockRange {
909                start_block,
910                end_block,
911            } => {
912                write!(
913                    f,
914                    "Invalid block range for partial decode: start_block {start_block} > end_block {end_block}"
915                )
916            }
917            #[cfg(feature = "lsm")]
918            FrameDecoderError::ResumeWindowTooShort { got, need } => {
919                write!(
920                    f,
921                    "resume window_prime too short: got {got} bytes, need at least {need}"
922                )
923            }
924            #[cfg(feature = "lsm")]
925            FrameDecoderError::ResumeFrameMismatch => {
926                write!(
927                    f,
928                    "resume state was captured from a frame with a different decode shape than the current frame"
929                )
930            }
931            #[cfg(feature = "lsm")]
932            FrameDecoderError::ResumeUnidentifiedDictionary => {
933                write!(
934                    f,
935                    "a dictionary with no ID cannot be told from another one, so it cannot carry a resume state across frames"
936                )
937            }
938        }
939    }
940}
941
942impl From<DictionaryDecodeError> for FrameDecoderError {
943    fn from(val: DictionaryDecodeError) -> Self {
944        Self::DictionaryDecodeError(val)
945    }
946}
947
948impl From<BlockHeaderReadError> for FrameDecoderError {
949    fn from(val: BlockHeaderReadError) -> Self {
950        Self::FailedToReadBlockHeader(val)
951    }
952}
953
954impl From<FrameHeaderError> for FrameDecoderError {
955    fn from(val: FrameHeaderError) -> Self {
956        Self::FrameHeaderError(val)
957    }
958}
959
960impl From<ReadFrameHeaderError> for FrameDecoderError {
961    fn from(val: ReadFrameHeaderError) -> Self {
962        Self::ReadFrameHeaderError(val)
963    }
964}
965
966#[derive(Debug)]
967#[non_exhaustive]
968pub enum DecompressLiteralsError {
969    MissingCompressedSize,
970    MissingNumStreams,
971    GetBitsError(GetBitsError),
972    HuffmanTableError(HuffmanTableError),
973    HuffmanDecoderError(HuffmanDecoderError),
974    UninitializedHuffmanTable,
975    MissingBytesForJumpHeader { got: usize },
976    MissingBytesForLiterals { got: usize, needed: usize },
977    ExtraPadding { skipped_bits: i32 },
978    BitstreamReadMismatch { read_til: isize, expected: isize },
979    DecodedLiteralCountMismatch { decoded: usize, expected: usize },
980}
981
982#[cfg(feature = "std")]
983impl std::error::Error for DecompressLiteralsError {
984    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
985        match self {
986            DecompressLiteralsError::GetBitsError(source) => Some(source),
987            DecompressLiteralsError::HuffmanTableError(source) => Some(source),
988            DecompressLiteralsError::HuffmanDecoderError(source) => Some(source),
989            _ => None,
990        }
991    }
992}
993impl core::fmt::Display for DecompressLiteralsError {
994    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
995        match self {
996            DecompressLiteralsError::MissingCompressedSize => {
997                write!(
998                    f,
999                    "compressed size was none even though it must be set to something for compressed literals",
1000                )
1001            }
1002            DecompressLiteralsError::MissingNumStreams => {
1003                write!(
1004                    f,
1005                    "num_streams was none even though it must be set to something (1 or 4) for compressed literals",
1006                )
1007            }
1008            DecompressLiteralsError::GetBitsError(e) => write!(f, "{e:?}"),
1009            DecompressLiteralsError::HuffmanTableError(e) => write!(f, "{e:?}"),
1010            DecompressLiteralsError::HuffmanDecoderError(e) => write!(f, "{e:?}"),
1011            DecompressLiteralsError::UninitializedHuffmanTable => {
1012                write!(
1013                    f,
1014                    "Tried to reuse huffman table but it was never initialized",
1015                )
1016            }
1017            DecompressLiteralsError::MissingBytesForJumpHeader { got } => {
1018                write!(f, "Need 6 bytes to decode jump header, got {got} bytes",)
1019            }
1020            DecompressLiteralsError::MissingBytesForLiterals { got, needed } => {
1021                write!(
1022                    f,
1023                    "Need at least {needed} bytes to decode literals. Have: {got} bytes",
1024                )
1025            }
1026            DecompressLiteralsError::ExtraPadding { skipped_bits } => {
1027                write!(
1028                    f,
1029                    "Padding at the end of the sequence_section was more than a byte long: {skipped_bits} bits. Probably caused by data corruption",
1030                )
1031            }
1032            DecompressLiteralsError::BitstreamReadMismatch { read_til, expected } => {
1033                write!(
1034                    f,
1035                    "Bitstream was read till: {read_til}, should have been: {expected}",
1036                )
1037            }
1038            DecompressLiteralsError::DecodedLiteralCountMismatch { decoded, expected } => {
1039                write!(
1040                    f,
1041                    "Did not decode enough literals: {decoded}, Should have been: {expected}",
1042                )
1043            }
1044        }
1045    }
1046}
1047
1048impl From<HuffmanDecoderError> for DecompressLiteralsError {
1049    fn from(val: HuffmanDecoderError) -> Self {
1050        Self::HuffmanDecoderError(val)
1051    }
1052}
1053
1054impl From<GetBitsError> for DecompressLiteralsError {
1055    fn from(val: GetBitsError) -> Self {
1056        Self::GetBitsError(val)
1057    }
1058}
1059
1060impl From<HuffmanTableError> for DecompressLiteralsError {
1061    fn from(val: HuffmanTableError) -> Self {
1062        Self::HuffmanTableError(val)
1063    }
1064}
1065
1066#[derive(Debug)]
1067#[non_exhaustive]
1068pub enum ExecuteSequencesError {
1069    DecodebufferError(DecodeBufferError),
1070    NotEnoughBytesForSequence {
1071        wanted: usize,
1072        have: usize,
1073    },
1074    ZeroOffset,
1075    /// An inline sequence (`exec_sequence_inline`) would have written past
1076    /// the writable tail of the output buffer. Raised by every capacity-bounded
1077    /// backend that runs the inline executor (the fixed-capacity user slice and
1078    /// the pre-reserved flat buffer alike). Indicates the frame is corrupt: its
1079    /// sequences expand past the declared `frame_content_size` plus the
1080    /// caller-supplied `WILDCOPY_OVERLENGTH` slack. The fast-path check is
1081    /// per-sequence; the post-block FCS overflow check would also catch the
1082    /// same shape, but the per-sequence guard is what keeps the unsafe write
1083    /// surface inside the buffer on the way to the post-block check.
1084    OutputBufferOverflow {
1085        tail: usize,
1086        requested: usize,
1087        capacity: usize,
1088    },
1089}
1090
1091impl core::fmt::Display for ExecuteSequencesError {
1092    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1093        match self {
1094            ExecuteSequencesError::DecodebufferError(e) => {
1095                write!(f, "{e:?}")
1096            }
1097            ExecuteSequencesError::NotEnoughBytesForSequence { wanted, have } => {
1098                write!(
1099                    f,
1100                    "Sequence wants to copy up to byte {wanted}. Bytes in literalsbuffer: {have}"
1101                )
1102            }
1103            ExecuteSequencesError::ZeroOffset => {
1104                write!(f, "Illegal offset: 0 found")
1105            }
1106            ExecuteSequencesError::OutputBufferOverflow {
1107                tail,
1108                requested,
1109                capacity,
1110            } => {
1111                write!(
1112                    f,
1113                    "Inline sequence would write past the output buffer: tail={tail}, requested={requested}, capacity={capacity}"
1114                )
1115            }
1116        }
1117    }
1118}
1119
1120#[cfg(feature = "std")]
1121impl std::error::Error for ExecuteSequencesError {
1122    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1123        match self {
1124            ExecuteSequencesError::DecodebufferError(source) => Some(source),
1125            _ => None,
1126        }
1127    }
1128}
1129
1130impl From<DecodeBufferError> for ExecuteSequencesError {
1131    fn from(val: DecodeBufferError) -> Self {
1132        Self::DecodebufferError(val)
1133    }
1134}
1135
1136impl From<crate::decoding::buffer_backend::BackendOverflow> for ExecuteSequencesError {
1137    fn from(val: crate::decoding::buffer_backend::BackendOverflow) -> Self {
1138        Self::OutputBufferOverflow {
1139            tail: val.tail,
1140            requested: val.requested,
1141            capacity: val.capacity,
1142        }
1143    }
1144}
1145
1146impl ExecuteSequencesError {
1147    /// `Some(requested)` when this error is a fixed-capacity output-buffer
1148    /// overshoot from the Compressed-block sequence executor — either the
1149    /// inline-sequence path ([`Self::OutputBufferOverflow`]) or the
1150    /// match-repeat fallback ([`DecodeBufferError::OutputBufferOverflow`]
1151    /// wrapped in [`Self::DecodebufferError`]). `requested` is the byte
1152    /// count the failing write tried to append past the slice end.
1153    ///
1154    /// `None` for every non-overflow variant. Used by
1155    /// `FrameDecoder::run_direct_decode` to fold an in-block Compressed
1156    /// overshoot into the same `FrameContentSizeMismatch` contract the
1157    /// Raw/RLE [`DecodeBlockContentError::BackendOverflow`] arm already
1158    /// produces — both mean "the frame's content expands past the
1159    /// declared `frame_content_size`".
1160    pub(crate) fn output_overflow_requested(&self) -> Option<usize> {
1161        match self {
1162            ExecuteSequencesError::OutputBufferOverflow { requested, .. } => Some(*requested),
1163            ExecuteSequencesError::DecodebufferError(DecodeBufferError::OutputBufferOverflow {
1164                requested,
1165                ..
1166            }) => Some(*requested),
1167            _ => None,
1168        }
1169    }
1170}
1171
1172#[derive(Debug)]
1173#[non_exhaustive]
1174pub enum DecodeSequenceError {
1175    GetBitsError(GetBitsError),
1176    FSEDecoderError(FSEDecoderError),
1177    FSETableError(FSETableError),
1178    ExtraPadding {
1179        skipped_bits: i32,
1180    },
1181    UnsupportedOffset {
1182        offset_code: u8,
1183    },
1184    ZeroOffset,
1185    NotEnoughBytesForNumSequences,
1186    ExtraBits {
1187        bits_remaining: isize,
1188    },
1189    MissingCompressionMode,
1190    MissingByteForRleLlTable,
1191    MissingByteForRleOfTable,
1192    MissingByteForRleMlTable,
1193    /// An RLE-mode sequence table's single symbol code is out of range
1194    /// for its axis (LL/ML/OF). `axis` names the axis; `code` is the
1195    /// offending value read from the stream.
1196    InvalidRleCode {
1197        axis: &'static str,
1198        code: u8,
1199    },
1200}
1201
1202#[cfg(feature = "std")]
1203impl std::error::Error for DecodeSequenceError {
1204    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1205        match self {
1206            DecodeSequenceError::GetBitsError(source) => Some(source),
1207            DecodeSequenceError::FSEDecoderError(source) => Some(source),
1208            DecodeSequenceError::FSETableError(source) => Some(source),
1209            _ => None,
1210        }
1211    }
1212}
1213
1214impl core::fmt::Display for DecodeSequenceError {
1215    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1216        match self {
1217            DecodeSequenceError::GetBitsError(e) => write!(f, "{e:?}"),
1218            DecodeSequenceError::FSEDecoderError(e) => write!(f, "{e:?}"),
1219            DecodeSequenceError::FSETableError(e) => write!(f, "{e:?}"),
1220            DecodeSequenceError::ExtraPadding { skipped_bits } => {
1221                write!(
1222                    f,
1223                    "Padding at the end of the sequence_section was more than a byte long: {skipped_bits} bits. Probably caused by data corruption",
1224                )
1225            }
1226            DecodeSequenceError::UnsupportedOffset { offset_code } => {
1227                write!(
1228                    f,
1229                    "Do not support offsets bigger than 1<<32; got: {offset_code}",
1230                )
1231            }
1232            DecodeSequenceError::ZeroOffset => write!(
1233                f,
1234                "Read an offset == 0. That is an illegal value for offsets"
1235            ),
1236            DecodeSequenceError::NotEnoughBytesForNumSequences => write!(
1237                f,
1238                "Bytestream did not contain enough bytes to decode num_sequences"
1239            ),
1240            DecodeSequenceError::ExtraBits { bits_remaining } => write!(f, "{bits_remaining}"),
1241            DecodeSequenceError::MissingCompressionMode => write!(
1242                f,
1243                "compression modes are none but they must be set to something"
1244            ),
1245            DecodeSequenceError::MissingByteForRleLlTable => {
1246                write!(f, "Need a byte to read for RLE ll table")
1247            }
1248            DecodeSequenceError::MissingByteForRleOfTable => {
1249                write!(f, "Need a byte to read for RLE of table")
1250            }
1251            DecodeSequenceError::MissingByteForRleMlTable => {
1252                write!(f, "Need a byte to read for RLE ml table")
1253            }
1254            DecodeSequenceError::InvalidRleCode { axis, code } => {
1255                write!(f, "RLE {axis} table code {code} is out of range")
1256            }
1257        }
1258    }
1259}
1260
1261impl From<GetBitsError> for DecodeSequenceError {
1262    fn from(val: GetBitsError) -> Self {
1263        Self::GetBitsError(val)
1264    }
1265}
1266
1267impl From<FSETableError> for DecodeSequenceError {
1268    fn from(val: FSETableError) -> Self {
1269        Self::FSETableError(val)
1270    }
1271}
1272
1273impl From<FSEDecoderError> for DecodeSequenceError {
1274    fn from(val: FSEDecoderError) -> Self {
1275        Self::FSEDecoderError(val)
1276    }
1277}
1278
1279#[derive(Debug)]
1280#[non_exhaustive]
1281pub enum LiteralsSectionParseError {
1282    IllegalLiteralSectionType { got: u8 },
1283    GetBitsError(GetBitsError),
1284    NotEnoughBytes { have: usize, need: u8 },
1285}
1286
1287#[cfg(feature = "std")]
1288impl std::error::Error for LiteralsSectionParseError {
1289    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1290        match self {
1291            LiteralsSectionParseError::GetBitsError(source) => Some(source),
1292            _ => None,
1293        }
1294    }
1295}
1296impl core::fmt::Display for LiteralsSectionParseError {
1297    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1298        match self {
1299            LiteralsSectionParseError::IllegalLiteralSectionType { got } => {
1300                write!(
1301                    f,
1302                    "Illegal literalssectiontype. Is: {got}, must be in: 0, 1, 2, 3"
1303                )
1304            }
1305            LiteralsSectionParseError::GetBitsError(e) => write!(f, "{e:?}"),
1306            LiteralsSectionParseError::NotEnoughBytes { have, need } => {
1307                write!(
1308                    f,
1309                    "Not enough byte to parse the literals section header. Have: {have}, Need: {need}",
1310                )
1311            }
1312        }
1313    }
1314}
1315
1316impl From<GetBitsError> for LiteralsSectionParseError {
1317    fn from(val: GetBitsError) -> Self {
1318        Self::GetBitsError(val)
1319    }
1320}
1321
1322impl core::fmt::Display for LiteralsSectionType {
1323    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
1324        match self {
1325            LiteralsSectionType::Compressed => write!(f, "Compressed"),
1326            LiteralsSectionType::Raw => write!(f, "Raw"),
1327            LiteralsSectionType::RLE => write!(f, "RLE"),
1328            LiteralsSectionType::Treeless => write!(f, "Treeless"),
1329        }
1330    }
1331}
1332
1333#[derive(Debug)]
1334#[non_exhaustive]
1335pub enum SequencesHeaderParseError {
1336    NotEnoughBytes { need_at_least: u8, got: usize },
1337}
1338
1339#[cfg(feature = "std")]
1340impl std::error::Error for SequencesHeaderParseError {}
1341
1342impl core::fmt::Display for SequencesHeaderParseError {
1343    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1344        match self {
1345            SequencesHeaderParseError::NotEnoughBytes { need_at_least, got } => {
1346                write!(
1347                    f,
1348                    "source must have at least {need_at_least} bytes to parse header; got {got} bytes",
1349                )
1350            }
1351        }
1352    }
1353}
1354
1355#[derive(Debug)]
1356#[non_exhaustive]
1357pub enum FSETableError {
1358    AccLogIsZero,
1359    AccLogTooBig {
1360        got: u8,
1361        max: u8,
1362    },
1363    GetBitsError(GetBitsError),
1364    ProbabilityCounterMismatch {
1365        got: u32,
1366        expected_sum: u32,
1367        symbol_probabilities: Vec<i32>,
1368    },
1369    TooManySymbols {
1370        got: usize,
1371    },
1372    /// Probability value outside the RFC 8878 §4.1.1 allowed set
1373    /// `{-1, 0, 1..=table_size}`. Carries the violating value, the
1374    /// table size (`1 << accuracy_log`) and `accuracy_log` so the
1375    /// caller can pinpoint the failure without re-deriving the bound.
1376    InvalidProbability {
1377        value: i32,
1378        table_size: u32,
1379        accuracy_log: u8,
1380    },
1381    /// `calc_baseline_and_numbits` produced a state-entry whose bit
1382    /// width exceeds the table's accuracy log, violating the
1383    /// `new_state + (1 << num_bits) - 1 < table_size` invariant that
1384    /// the unchecked `read_entry` decode hot path relies on. The
1385    /// triggering probability is in-range per RFC 8878 §4.1.1; the
1386    /// failure is an internal table-shape inconsistency surfaced
1387    /// against the public `build_from_probabilities` API.
1388    TableInvariantViolation {
1389        prob: i32,
1390        symbol: u8,
1391        num_bits: u8,
1392        accuracy_log: u8,
1393    },
1394}
1395
1396#[cfg(feature = "std")]
1397impl std::error::Error for FSETableError {
1398    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1399        match self {
1400            FSETableError::GetBitsError(source) => Some(source),
1401            _ => None,
1402        }
1403    }
1404}
1405
1406impl core::fmt::Display for FSETableError {
1407    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1408        match self {
1409            FSETableError::AccLogIsZero => write!(f, "Acclog must be at least 1"),
1410            FSETableError::AccLogTooBig { got, max } => {
1411                write!(
1412                    f,
1413                    "Found FSE acc_log: {got} bigger than allowed maximum in this case: {max}"
1414                )
1415            }
1416            FSETableError::GetBitsError(e) => write!(f, "{e:?}"),
1417            FSETableError::ProbabilityCounterMismatch {
1418                got,
1419                expected_sum,
1420                symbol_probabilities,
1421            } => {
1422                write!(
1423                    f,
1424                    "FSE probability sum mismatch: got {got}, expected {expected_sum}. Indicates corrupted data or an invalid distribution\n {symbol_probabilities:?}",
1425                )
1426            }
1427            FSETableError::TooManySymbols { got } => {
1428                write!(
1429                    f,
1430                    "There are too many symbols in this distribution: {got}. Max: 256",
1431                )
1432            }
1433            FSETableError::InvalidProbability {
1434                value,
1435                table_size,
1436                accuracy_log,
1437            } => {
1438                write!(
1439                    f,
1440                    "FSE probability value {value} is outside the RFC 8878 allowed set (must be -1, 0, or in 1..={table_size}; accuracy_log={accuracy_log})",
1441                )
1442            }
1443            FSETableError::TableInvariantViolation {
1444                prob,
1445                symbol,
1446                num_bits,
1447                accuracy_log,
1448            } => {
1449                write!(
1450                    f,
1451                    "FSE table invariant violation: symbol {symbol} (prob {prob}) produced num_bits {num_bits} > accuracy_log {accuracy_log}",
1452                )
1453            }
1454        }
1455    }
1456}
1457
1458impl From<GetBitsError> for FSETableError {
1459    fn from(val: GetBitsError) -> Self {
1460        Self::GetBitsError(val)
1461    }
1462}
1463
1464#[derive(Debug)]
1465#[non_exhaustive]
1466pub enum FSEDecoderError {
1467    GetBitsError(GetBitsError),
1468    TableIsUninitialized,
1469    /// Externally constructed `FSETable` violates the
1470    /// `decode.len() == 1 << accuracy_log` shape invariant. Only
1471    /// reachable under `feature = "fuzz-exports"`, where fuzz
1472    /// harnesses can set the `FSETable.decode` / `accuracy_log`
1473    /// fields directly and skip `build_decoding_table`.
1474    InvalidTableShape {
1475        decode_len: usize,
1476        accuracy_log: u8,
1477    },
1478}
1479
1480#[cfg(feature = "std")]
1481impl std::error::Error for FSEDecoderError {
1482    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1483        match self {
1484            FSEDecoderError::GetBitsError(source) => Some(source),
1485            _ => None,
1486        }
1487    }
1488}
1489
1490impl core::fmt::Display for FSEDecoderError {
1491    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1492        match self {
1493            FSEDecoderError::GetBitsError(e) => write!(f, "{e:?}"),
1494            FSEDecoderError::TableIsUninitialized => {
1495                write!(f, "Tried to use an uninitialized table!")
1496            }
1497            FSEDecoderError::InvalidTableShape {
1498                decode_len,
1499                accuracy_log,
1500            } => match 1usize.checked_shl((*accuracy_log).into()) {
1501                Some(expected) => write!(
1502                    f,
1503                    "FSETable shape invariant violated: decode.len() = {decode_len}, expected 1 << accuracy_log = {expected} (accuracy_log = {accuracy_log})",
1504                ),
1505                None => write!(
1506                    f,
1507                    "FSETable shape invariant violated: decode.len() = {decode_len}, accuracy_log = {accuracy_log} overflows 1 << accuracy_log for usize",
1508                ),
1509            },
1510        }
1511    }
1512}
1513
1514impl From<GetBitsError> for FSEDecoderError {
1515    fn from(val: GetBitsError) -> Self {
1516        Self::GetBitsError(val)
1517    }
1518}
1519
1520#[derive(Debug)]
1521#[non_exhaustive]
1522pub enum HuffmanTableError {
1523    GetBitsError(GetBitsError),
1524    FSEDecoderError(FSEDecoderError),
1525    FSETableError(FSETableError),
1526    SourceIsEmpty,
1527    NotEnoughBytesForWeights {
1528        got_bytes: usize,
1529        expected_bytes: u8,
1530    },
1531    ExtraPadding {
1532        skipped_bits: i32,
1533    },
1534    TooManyWeights {
1535        got: usize,
1536    },
1537    MissingWeights,
1538    LeftoverIsNotAPowerOf2 {
1539        got: u32,
1540    },
1541    NotEnoughBytesToDecompressWeights {
1542        have: usize,
1543        need: usize,
1544    },
1545    FSETableUsedTooManyBytes {
1546        used: usize,
1547        available_bytes: u8,
1548    },
1549    NotEnoughBytesInSource {
1550        got: usize,
1551        need: usize,
1552    },
1553    WeightBiggerThanMaxNumBits {
1554        got: u8,
1555    },
1556    MaxBitsTooHigh {
1557        got: u8,
1558    },
1559}
1560
1561#[cfg(feature = "std")]
1562impl StdError for HuffmanTableError {
1563    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1564        match self {
1565            HuffmanTableError::GetBitsError(source) => Some(source),
1566            HuffmanTableError::FSEDecoderError(source) => Some(source),
1567            HuffmanTableError::FSETableError(source) => Some(source),
1568            _ => None,
1569        }
1570    }
1571}
1572
1573impl core::fmt::Display for HuffmanTableError {
1574    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> ::core::fmt::Result {
1575        match self {
1576            HuffmanTableError::GetBitsError(e) => write!(f, "{e:?}"),
1577            HuffmanTableError::FSEDecoderError(e) => write!(f, "{e:?}"),
1578            HuffmanTableError::FSETableError(e) => write!(f, "{e:?}"),
1579            HuffmanTableError::SourceIsEmpty => write!(f, "Source needs to have at least one byte"),
1580            HuffmanTableError::NotEnoughBytesForWeights {
1581                got_bytes,
1582                expected_bytes,
1583            } => {
1584                write!(
1585                    f,
1586                    "Header says there should be {expected_bytes} bytes for the weights but there are only {got_bytes} bytes in the stream"
1587                )
1588            }
1589            HuffmanTableError::ExtraPadding { skipped_bits } => {
1590                write!(
1591                    f,
1592                    "Padding at the end of the sequence_section was more than a byte long: {skipped_bits} bits. Probably caused by data corruption",
1593                )
1594            }
1595            HuffmanTableError::TooManyWeights { got } => {
1596                write!(
1597                    f,
1598                    "More than 255 weights decoded (got {got} weights). Stream is probably corrupted",
1599                )
1600            }
1601            HuffmanTableError::MissingWeights => {
1602                write!(f, "Can\'t build huffman table without any weights")
1603            }
1604            HuffmanTableError::LeftoverIsNotAPowerOf2 { got } => {
1605                write!(f, "Leftover must be power of two but is: {got}")
1606            }
1607            HuffmanTableError::NotEnoughBytesToDecompressWeights { have, need } => {
1608                write!(
1609                    f,
1610                    "Not enough bytes in stream to decompress weights. Is: {have}, Should be: {need}",
1611                )
1612            }
1613            HuffmanTableError::FSETableUsedTooManyBytes {
1614                used,
1615                available_bytes,
1616            } => {
1617                write!(
1618                    f,
1619                    "FSE table used more bytes: {used} than were meant to be used for the whole stream of huffman weights ({available_bytes})",
1620                )
1621            }
1622            HuffmanTableError::NotEnoughBytesInSource { got, need } => {
1623                write!(f, "Source needs to have at least {need} bytes, got: {got}",)
1624            }
1625            HuffmanTableError::WeightBiggerThanMaxNumBits { got } => {
1626                write!(
1627                    f,
1628                    "Cant have weight: {} bigger than max_num_bits: {}",
1629                    got,
1630                    crate::huff0::MAX_MAX_NUM_BITS,
1631                )
1632            }
1633            HuffmanTableError::MaxBitsTooHigh { got } => {
1634                write!(
1635                    f,
1636                    "max_bits derived from weights is: {} should be lower than: {}",
1637                    got,
1638                    crate::huff0::MAX_MAX_NUM_BITS,
1639                )
1640            }
1641        }
1642    }
1643}
1644
1645impl From<GetBitsError> for HuffmanTableError {
1646    fn from(val: GetBitsError) -> Self {
1647        Self::GetBitsError(val)
1648    }
1649}
1650
1651impl From<FSEDecoderError> for HuffmanTableError {
1652    fn from(val: FSEDecoderError) -> Self {
1653        Self::FSEDecoderError(val)
1654    }
1655}
1656
1657impl From<FSETableError> for HuffmanTableError {
1658    fn from(val: FSETableError) -> Self {
1659        Self::FSETableError(val)
1660    }
1661}
1662
1663#[derive(Debug)]
1664#[non_exhaustive]
1665pub enum HuffmanDecoderError {
1666    GetBitsError(GetBitsError),
1667}
1668
1669impl core::fmt::Display for HuffmanDecoderError {
1670    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1671        match self {
1672            HuffmanDecoderError::GetBitsError(e) => write!(f, "{e:?}"),
1673        }
1674    }
1675}
1676
1677#[cfg(feature = "std")]
1678impl StdError for HuffmanDecoderError {
1679    fn source(&self) -> Option<&(dyn StdError + 'static)> {
1680        match self {
1681            HuffmanDecoderError::GetBitsError(source) => Some(source),
1682        }
1683    }
1684}
1685
1686impl From<GetBitsError> for HuffmanDecoderError {
1687    fn from(val: GetBitsError) -> Self {
1688        Self::GetBitsError(val)
1689    }
1690}
1691
1692#[cfg(test)]
1693mod tests;