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