Skip to main content

structured_zstd/decoding/
frame_decoder.rs

1//! Framedecoder is the main low-level struct users interact with to decode zstd frames
2//!
3//! Zstandard compressed data is made of one or more frames. Each frame is independent and can be
4//! decompressed independently of other frames. This module contains structures
5//! and utilities that can be used to decode a frame.
6
7use super::frame;
8use crate::decoding;
9use crate::decoding::block_decoder::BlockDecoder;
10use crate::decoding::buffer_backend::BufferBackend;
11use crate::decoding::dictionary::{Dictionary, DictionaryHandle};
12use crate::decoding::errors::{DecodeBlockContentError, FrameDecoderError};
13use crate::decoding::flat_buf::FlatBuf;
14use crate::decoding::ringbuffer::RingBuffer;
15use crate::decoding::scratch::DecoderScratch;
16use crate::io::{Error, Read, Write};
17use alloc::collections::BTreeMap;
18use alloc::vec::Vec;
19use core::convert::TryInto;
20
21use crate::common::MAXIMUM_ALLOWED_WINDOW_SIZE;
22
23/// Build the block-header decode error. With the `lsm` feature it captures
24/// the failing block's index and frame offset (block-precise recovery);
25/// without it, the legacy positionless variant — so the default build's
26/// error surface stays byte-identical to the upstream zstd.
27#[cfg(feature = "lsm")]
28fn block_header_decode_error(
29    source: crate::decoding::errors::BlockHeaderReadError,
30    block_index: u32,
31    frame_offset: u32,
32) -> FrameDecoderError {
33    FrameDecoderError::FailedToReadBlockHeaderAt {
34        source,
35        block_index,
36        frame_offset,
37    }
38}
39#[cfg(not(feature = "lsm"))]
40fn block_header_decode_error(
41    source: crate::decoding::errors::BlockHeaderReadError,
42    _block_index: u32,
43    _frame_offset: u32,
44) -> FrameDecoderError {
45    FrameDecoderError::FailedToReadBlockHeader(source)
46}
47
48/// Build the block-body decode error. With `lsm` it captures the block
49/// index, frame offset, and the failing block's structural metadata
50/// (reconstructed from its header); without it, the legacy variant.
51#[cfg(feature = "lsm")]
52fn block_body_decode_error(
53    source: DecodeBlockContentError,
54    block_index: u32,
55    frame_offset: u32,
56    header: &crate::blocks::block::BlockHeader,
57    header_size: u8,
58) -> FrameDecoderError {
59    use crate::blocks::block::BlockType;
60    // Physical wire body vs the raw `Block_Size` field: RLE writes a single
61    // body byte while `Block_Size` carries the repeat count; Raw/Compressed
62    // bodies match the field.
63    let (body_size, block_size_field) = match header.block_type {
64        BlockType::RLE => (1u32, header.decompressed_size),
65        _ => (header.content_size, header.content_size),
66    };
67    FrameDecoderError::FailedToReadBlockBodyAt {
68        source,
69        block_index,
70        frame_offset,
71        block: crate::encoding::frame_emit_info::FrameBlock {
72            offset_in_frame: frame_offset,
73            header_size,
74            body_size,
75            block_size_field,
76            block_type: header.block_type,
77            last_block: header.last_block,
78            // Raw/RLE carry their regenerated size in the header;
79            // a Compressed block's is unknown until decoded, so
80            // `read_block_header` leaves `decompressed_size` 0 here.
81            decompressed_size: header.decompressed_size,
82        },
83    }
84}
85#[cfg(not(feature = "lsm"))]
86fn block_body_decode_error(
87    source: DecodeBlockContentError,
88    _block_index: u32,
89    _frame_offset: u32,
90    _header: &crate::blocks::block::BlockHeader,
91    _header_size: u8,
92) -> FrameDecoderError {
93    FrameDecoderError::FailedToReadBlockBody(source)
94}
95
96/// Low level Zstandard decoder that can be used to decompress frames with fine control over when and how many bytes are decoded.
97///
98/// This decoder is able to decode frames only partially and gives control
99/// over how many bytes/blocks will be decoded at a time (so you don't have to decode a 10GB file into memory all at once).
100/// It reads bytes as needed from a provided source and can be read from to collect partial results.
101///
102/// If you want to just read the whole frame with an `io::Read` without having to deal with manually calling [FrameDecoder::decode_blocks]
103/// you can use the provided [crate::decoding::StreamingDecoder] wich wraps this FrameDecoder.
104///
105/// Workflow is as follows:
106/// ```
107/// use structured_zstd::decoding::BlockDecodingStrategy;
108///
109/// # #[cfg(feature = "std")]
110/// use std::io::{Read, Write};
111///
112/// // no_std environments can use the crate's own Read traits
113/// # #[cfg(not(feature = "std"))]
114/// use structured_zstd::io::{Read, Write};
115///
116/// fn decode_this(mut file: impl Read) {
117///     //Create a new decoder
118///     let mut frame_dec = structured_zstd::decoding::FrameDecoder::new();
119///     let mut result = Vec::new();
120///
121///     // Use reset or init to make the decoder ready to decode the frame from the io::Read
122///     frame_dec.reset(&mut file).unwrap();
123///
124///     // Loop until the frame has been decoded completely
125///     while !frame_dec.is_finished() {
126///         // decode (roughly) batch_size many bytes
127///         frame_dec.decode_blocks(&mut file, BlockDecodingStrategy::UptoBytes(1024)).unwrap();
128///
129///         // read from the decoder to collect bytes from the internal buffer
130///         let bytes_read = frame_dec.read(result.as_mut_slice()).unwrap();
131///
132///         // then do something with it
133///         do_something(&result[0..bytes_read]);
134///     }
135///
136///     // handle the last chunk of data
137///     while frame_dec.can_collect() > 0 {
138///         let x = frame_dec.read(result.as_mut_slice()).unwrap();
139///
140///         do_something(&result[0..x]);
141///     }
142/// }
143///
144/// fn do_something(data: &[u8]) {
145/// # #[cfg(feature = "std")]
146///     std::io::stdout().write_all(data).unwrap();
147/// }
148/// ```
149pub struct FrameDecoder {
150    state: Option<FrameDecoderState>,
151    /// Test-only observability: frames decoded via `run_direct_decode`.
152    /// The direct and buffered paths are byte-identical, so dispatch
153    /// regressions (e.g. re-excluding dictionary frames from the direct
154    /// gate) are invisible to output assertions; tests pin the path here.
155    #[cfg(test)]
156    direct_frames: u64,
157    // Registered dictionaries are stored by shared handle (Arc/Rc) so a
158    // single content copy is referenced by every frame the decoder decodes
159    // (upstream zstd `ZSTD_refDDict`), rather than re-copied into the decode buffer
160    // per frame. `add_dict` wraps an owned `Dictionary` into a handle.
161    owned_dicts: BTreeMap<u32, DictionaryHandle>,
162    #[cfg(target_has_atomic = "ptr")]
163    shared_dicts: BTreeMap<u32, DictionaryHandle>,
164    #[cfg(not(target_has_atomic = "ptr"))]
165    shared_dicts: (),
166    /// `ZSTD_f_zstd1_magicless` — when true, [`init`] / [`reset`]
167    /// expect frames without the 4-byte magic number prefix.
168    /// Default false (standard zstd format).
169    magicless: bool,
170    /// How the optional content checksum is handled. Default
171    /// [`ContentChecksum::EmitOnly`] (compute + expose, no error on
172    /// mismatch). Set via [`Self::set_content_checksum`].
173    content_checksum: ContentChecksum,
174    /// Pinned `Dictionary_ID` expectation set via
175    /// [`Self::expect_dict_id`]. `None` (default) disables the
176    /// check; `Some(0)` matches frames whose header omits the
177    /// optional dict_id (treated as "no dictionary"). Validated in
178    /// [`Self::reset`] AFTER the frame header parses successfully
179    /// and BEFORE any block decode work.
180    #[cfg(feature = "lsm")]
181    expect_dict_id: Option<u32>,
182    /// Pinned `Window_Descriptor` byte expectation set via
183    /// [`Self::expect_window_descriptor`]. `None` (default)
184    /// disables the check. Validated in [`Self::reset`] AFTER the
185    /// frame header parses successfully and BEFORE any block
186    /// decode work. Single-segment frames (which omit the
187    /// `Window_Descriptor` byte from the wire) surface as
188    /// [`crate::decoding::errors::FrameDecoderError::UnexpectedWindowDescriptor`]
189    /// with `found: None`.
190    #[cfg(feature = "lsm")]
191    expect_window_descriptor: Option<u8>,
192    /// When `true`, the per-block decode loop XXH64-hashes each
193    /// block's decompressed bytes and stores the low-32-bit digest in
194    /// [`Self::computed_block_checksums`]. Default `false` (zero
195    /// cost). Set via [`Self::enable_per_block_checksums`]. Gated on
196    /// `all(lsm, hash)` because XXH64 lives behind the `hash`
197    /// feature.
198    #[cfg(all(feature = "lsm", feature = "hash"))]
199    per_block_checksums_enabled: bool,
200    /// Per-block XXH64 (low 32 bits) digests captured during the
201    /// current frame's decode when `per_block_checksums_enabled` is
202    /// set. Reset at the start of every new frame. Gated on
203    /// `all(lsm, hash)` (see `per_block_checksums_enabled`).
204    #[cfg(all(feature = "lsm", feature = "hash"))]
205    computed_block_checksums: alloc::vec::Vec<u32>,
206}
207
208/// How the decoder treats a frame's optional XXH64 content checksum
209/// (RFC 8878 Content_Checksum_flag). The XXH64 pass over the decompressed
210/// output is a measurable share of decode time, so it is made skippable.
211///
212/// ```
213/// use structured_zstd::decoding::{ContentChecksum, FrameDecoder};
214/// let mut decoder = FrameDecoder::new();
215/// decoder.set_content_checksum(ContentChecksum::Verify);
216/// ```
217#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
218pub enum ContentChecksum {
219    /// Skip the XXH64 pass entirely: no compute, no verify.
220    /// `get_calculated_checksum()` returns `None`.
221    None,
222    /// Compute the checksum and expose it via the accessors, but do not
223    /// error on a mismatch. This is the default and matches the historical
224    /// behaviour (callers verify manually if they wish).
225    #[default]
226    EmitOnly,
227    /// Compute the checksum and compare it against the frame's stored value;
228    /// a disagreement fails the decode with
229    /// [`FrameDecoderError::ChecksumMismatch`](crate::decoding::errors::FrameDecoderError::ChecksumMismatch).
230    /// Without the `hash` feature there is no way to compute a digest, so
231    /// `Verify` cannot detect a mismatch and behaves like `None`.
232    Verify,
233}
234
235/// Decode-relevant identity of a frame, used to reject a [`ResumeState`]
236/// captured from one frame being applied to a frame of a different shape. Covers
237/// every header field that changes how blocks decode (buffer sizing, backend
238/// kind, entropy/dictionary context, trailing-checksum handling, declared
239/// content size, magicless framing).
240///
241/// This is a SHAPE guard, not a content-unique fingerprint: two distinct frames
242/// that happen to share all these header fields produce the same key (no cheap
243/// header field uniquely identifies frame content). It catches the realistic
244/// accidental misuse — applying a snapshot to a frame with a different
245/// window/dictionary/size — with a typed error instead of byte-wrong output.
246/// Pairing a `ResumeState` with the correct frame's compressed source and
247/// `window_prime` remains the caller's contract.
248#[cfg(feature = "lsm")]
249#[derive(Clone, Copy, PartialEq, Eq, Debug)]
250struct FrameKey {
251    window_size: u64,
252    frame_content_size: u64,
253    /// `Dictionary_ID` declared in the frame header (`None` when omitted).
254    dictionary_id: Option<u32>,
255    /// Dictionary actually applied to the decoder (`state.using_dict`). This is
256    /// distinct from `dictionary_id`: a frame with a dictless header can still
257    /// be decoded with an explicit dictionary via `reset_with_dict_handle` /
258    /// `force_dict`, and two such decodes with different dictionaries must NOT
259    /// compare equal — keying only on the header field would miss that.
260    active_dictionary_id: Option<u32>,
261    single_segment: bool,
262    content_checksum: bool,
263    magicless: bool,
264}
265
266#[cfg(feature = "lsm")]
267impl FrameKey {
268    fn from_state(state: &FrameDecoderState, magicless: bool) -> FrameKey {
269        let header = &state.frame_header;
270        FrameKey {
271            window_size: header.window_size().unwrap_or(0),
272            frame_content_size: header.frame_content_size(),
273            dictionary_id: header.dictionary_id(),
274            active_dictionary_id: state.using_dict,
275            single_segment: header.descriptor.single_segment_flag(),
276            content_checksum: header.descriptor.content_checksum_flag(),
277            magicless,
278        }
279    }
280}
281
282/// XXH64 of a contiguous byte slice — the resume-side counterpart to
283/// [`DecoderScratchKind::window_tail_hash`]. Streaming XXH64 is chunk-boundary
284/// independent, so this single-slice hash equals the emit-side two-slice hash
285/// over the same bytes.
286#[cfg(all(feature = "lsm", feature = "hash"))]
287fn xxh64_of(bytes: &[u8]) -> u64 {
288    use core::hash::Hasher;
289    let mut h = twox_hash::XxHash64::with_seed(0);
290    h.write(bytes);
291    h.finish()
292}
293
294/// Cross-block decode state needed to resume a cold partial decode at an inner
295/// block boundary, emitted by [`FrameDecoder::decode_blocks_partial`] when its
296/// `emit_resume` argument is `true` (returned in
297/// [`PartialDecode::resume_state`]) and fed back via that same method's
298/// [`resume`](FrameDecoder::decode_blocks_partial) argument
299/// ([`ResumeInput`]).
300///
301/// A zstd block does not carry all the state required to decode it in
302/// isolation: besides the shared match window (the decompressed output history),
303/// a Compressed block may reuse the previous block's entropy tables via
304/// `Repeat_Mode` (literals Huffman + the LL/OF/ML FSE distributions) and always
305/// continues the running repeat-offset history. This snapshot carries exactly
306/// that carry-over state plus the resume coordinates, so resuming is
307/// byte-identical to a contiguous decode even across a dropped decoder. The
308/// window itself is NOT stored here — the caller supplies it back through
309/// [`ResumeInput::window_prime`] from the decompressed output it already
310/// persists. Neither is the dictionary: for a dictionary frame the caller
311/// re-attaches it to the resuming decoder via [`FrameDecoder::reset`] /
312/// [`FrameDecoder::reset_with_dict_handle`] (it already holds the dictionary
313/// from encode time), and the snapshot records only the dictionary's identity
314/// so a resume under a different dictionary is rejected.
315///
316/// Behind the `lsm` Cargo feature.
317#[cfg(feature = "lsm")]
318#[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
319pub struct ResumeState {
320    /// Identity of the frame this state was captured from. Compared against the
321    /// frame currently reset into the decoder before any state is restored, so a
322    /// snapshot from a different frame shape is rejected with
323    /// [`FrameDecoderError::ResumeFrameMismatch`] instead of silently producing
324    /// byte-wrong output.
325    frame_key: FrameKey,
326    /// Index of the block to resume AT (the first block NOT yet decoded).
327    block_index: u32,
328    /// Cumulative decompressed byte count produced before `block_index`.
329    output_offset: u64,
330    /// FSE tables (LL/OF/ML) as of the last decoded block — the source for a
331    /// `Repeat_Mode` resume block.
332    fse: crate::decoding::scratch::FSEScratch,
333    /// Huffman literals table as of the last decoded block — the source for a
334    /// treeless (repeat) literals resume block.
335    huf: crate::decoding::scratch::HuffmanScratch,
336    /// Running repeat-offset history (`offset_hist`) as of the last decoded
337    /// block.
338    offset_hist: [u32; 3],
339    /// XXH64 of the exact window-prime bytes (the last `min(window_size,
340    /// output_offset)` decompressed bytes) captured at emit. Verified at resume
341    /// against the caller-supplied [`ResumeInput::window_prime`]: a content
342    /// mismatch (wrong frame, wrong or corrupted prime) is a near-unique
343    /// (≈2⁻⁶⁴) signal and is rejected with
344    /// [`FrameDecoderError::ResumeFrameMismatch`]. This is the content-exact
345    /// guard; [`FrameKey`] is the cheap shape pre-check that works without the
346    /// `hash` feature. Behind `all(lsm, hash)`.
347    #[cfg(feature = "hash")]
348    window_hash: u64,
349}
350
351#[cfg(feature = "lsm")]
352impl ResumeState {
353    /// Inner block index this state resumes at (the first block not yet
354    /// decoded). Pass it as the `end_block` lower bound (and as `start_block`)
355    /// of the resuming
356    /// [`decode_blocks_partial`](FrameDecoder::decode_blocks_partial) call.
357    pub fn block_index(&self) -> u32 {
358        self.block_index
359    }
360
361    /// Cumulative decompressed byte count produced before
362    /// [`block_index`](Self::block_index) — i.e. the decompressed offset at
363    /// which the resumed output begins. Equals
364    /// `FrameEmitInfo::decompressed_byte_range(block_index).start`. Use it to
365    /// slice the `window_prime` tail the resumed call needs.
366    pub fn output_offset(&self) -> u64 {
367        self.output_offset
368    }
369}
370
371// Manual Debug: the entropy tables are large internal scratch with no useful
372// Debug surface; only the resume coordinates are worth printing (and this lets
373// `PartialDecode` keep its derived Debug).
374#[cfg(feature = "lsm")]
375impl core::fmt::Debug for ResumeState {
376    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
377        f.debug_struct("ResumeState")
378            .field("block_index", &self.block_index)
379            .field("output_offset", &self.output_offset)
380            .finish_non_exhaustive()
381    }
382}
383
384/// Resume input fed to [`FrameDecoder::decode_blocks_partial`]'s `resume`
385/// argument to continue a cold partial decode without re-decompressing the
386/// preceding blocks.
387///
388/// Behind the `lsm` Cargo feature.
389#[cfg(feature = "lsm")]
390#[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
391pub struct ResumeInput<'a> {
392    /// The caller's already-decompressed output ending just before
393    /// [`ResumeState::block_index`]. Must contain at least the last
394    /// `min(window_size, output_offset)` bytes (a full match window, or the
395    /// whole prefix when it is shorter than one window); anything beyond the
396    /// last `window_size` bytes is ignored, so passing the entire prefix is
397    /// also valid (capped internally, bounding resume memory to one window).
398    pub window_prime: &'a [u8],
399    /// Cross-block entropy/repcode state emitted by the prior
400    /// [`decode_blocks_partial`](FrameDecoder::decode_blocks_partial) call.
401    pub state: &'a ResumeState,
402}
403
404/// Backend-tagged decode scratch — chosen at frame-reset time based
405/// on the parsed `FrameHeader.descriptor.single_segment_flag()` and
406/// kept stable through the lifetime of the frame. The match in each
407/// helper below dispatches **once per call** (e.g. once per block in
408/// `decode_block_content`, once per drain in `drain_to_writer`) —
409/// never inside the hot push/repeat loop, which is fully
410/// monomorphised through the `DecoderScratch<B>` generic.
411enum DecoderScratchKind {
412    Ring(DecoderScratch<RingBuffer>),
413    Flat(DecoderScratch<FlatBuf>),
414}
415
416impl DecoderScratchKind {
417    fn new_ring(window_size: usize) -> Self {
418        // Lazy ring-buffer allocation: do NOT `reserve(window_size)` here.
419        // The direct-decode path (`run_direct_decode`) writes through
420        // `UserSliceBackend` and never touches the ring; allocating it
421        // eagerly wastes one full window of peak memory on the common
422        // direct-eligible frame. On the non-direct path the window is
423        // pre-reserved once at frame entry (`decode_all_impl` and
424        // `decode_blocks` both call `DecoderScratchKind::reserve_buffer`
425        // before any block writes), so multi-block frames pay one
426        // amortised grow instead of repeated `reserve_amortized` steps
427        // per block. Issue #279 round 2.
428        let s = DecoderScratch::<RingBuffer>::new(window_size);
429        Self::Ring(s)
430    }
431
432    /// Construct a flat-backed scratch for a single-segment frame.
433    /// `frame_content_size` is the upcoming output size in bytes
434    /// (== `window_size` when the flag is set).
435    ///
436    /// Lazy buffer allocation (mirrors [`Self::new_ring`]): do NOT
437    /// pre-size the `FlatBuf`. The direct-decode path
438    /// (`run_direct_decode`) writes through `UserSliceBackend` and never
439    /// touches this buffer, so eagerly allocating a full FCS wastes one
440    /// whole content-size of peak memory on the common direct-eligible
441    /// single-segment frame. The non-direct fallback reserves it once via
442    /// `reserve_buffer(window_size)` at frame entry before any block
443    /// write (`FlatBuf::reserve` adds the `WILDCOPY_OVERLENGTH` slack),
444    /// and every inline-exec site (trait method and per-kernel macros)
445    /// now carries a tight-tail bounded copy, so a tight buffer can never
446    /// overshoot regardless of construction-time slack.
447    fn new_flat(frame_content_size: usize) -> Self {
448        let s = DecoderScratch::<FlatBuf>::new(frame_content_size);
449        Self::Flat(s)
450    }
451
452    /// Reset (or transition between) backends for a new frame.
453    /// Reuses the existing `DecoderScratch` allocations (FSE / HUF
454    /// tables, sequence vec, etc.) when the backend kind is unchanged
455    /// — only the underlying buffer is re-sized for the new frame.
456    /// Building a fresh `DecoderScratch` on every frame would
457    /// re-allocate everything and was measured at +255 % vs ring on
458    /// small frames; reusing it keeps the small-frame cost flat.
459    fn reset(&mut self, frame: &frame::FrameHeader, window_size: usize) {
460        if frame.descriptor.single_segment_flag() {
461            match self {
462                Self::Flat(s) => {
463                    s.reset(window_size);
464                    // `DecoderScratch::reset` clears the backing buffer and
465                    // updates `window_size` WITHOUT reserving it (it may still
466                    // resize the per-block scratch Vecs up to
467                    // `min(window_size, MAX_BLOCK_SIZE)`). Backing-buffer
468                    // capacity is decided one layer up: direct-eligible frames
469                    // never touch it, and the non-direct path pre-reserves once
470                    // via `reserve_buffer(window_size)` at frame entry.
471                }
472                Self::Ring(_) => *self = Self::new_flat(window_size),
473            }
474        } else {
475            match self {
476                Self::Ring(s) => s.reset(window_size),
477                Self::Flat(_) => *self = Self::new_ring(window_size),
478            }
479        }
480    }
481
482    fn init_from_dict(&mut self, dict: &DictionaryHandle) {
483        match self {
484            Self::Ring(s) => s.init_from_dict(dict),
485            Self::Flat(s) => s.init_from_dict(dict),
486        }
487    }
488
489    #[inline]
490    fn buffer_len(&self) -> usize {
491        match self {
492            Self::Ring(s) => s.buffer.len(),
493            Self::Flat(s) => s.buffer.len(),
494        }
495    }
496
497    fn workspace_bytes(&self) -> usize {
498        match self {
499            Self::Ring(s) => s.workspace_bytes(),
500            Self::Flat(s) => s.workspace_bytes(),
501        }
502    }
503
504    /// Pre-reserve the backing buffer to `window_size` in a single
505    /// allocation. Called once on the non-direct (`decode_blocks`) path
506    /// after direct-eligibility is ruled out, so multi-segment fallback
507    /// decodes don't pay repeated `reserve_amortized` grow steps
508    /// (128 KiB → 256 KiB → ... → window) as blocks accumulate.
509    ///
510    /// Direct-eligible frames never call this and pay zero backing-buffer
511    /// allocation for the window, on BOTH backends: `new_ring` and
512    /// `new_flat` are each lazy (no pre-reserve), so a direct-eligible
513    /// frame writes only through `UserSliceBackend` and leaves this
514    /// buffer empty.
515    ///
516    /// `window_size` is the TARGET visible-window capacity: callers pass
517    /// the full window, and the method itself computes the shortfall past
518    /// the bytes already buffered before calling the backend's
519    /// ADDITIONAL-semantics `reserve_exact`. That keeps re-entries (the
520    /// decode_all fallback loop runs `decode_blocks` once per strategy
521    /// chunk, and streaming callers invoke it per call) from growing a
522    /// window-full buffer toward 2x window, while per-block growth keeps
523    /// the amortized `reserve`.
524    #[inline]
525    fn reserve_buffer(&mut self, window_size: usize) {
526        // Exact growth: this is the one-shot pre-reservation, and a request
527        // landing one slack past the retained capacity (e.g. a dictionary
528        // prefix already loaded into the buffer) must not DOUBLE a
529        // window-sized allocation through the amortized policy. Per-block
530        // growth keeps the amortized `reserve`.
531        //
532        // `reserve_exact` takes ADDITIONAL capacity, so request only the
533        // shortfall past the bytes already buffered: the decode_all
534        // fallback loop re-enters `decode_blocks` once per strategy chunk,
535        // and re-requesting the full window each iteration would grow a
536        // window-sized buffer toward 2x window.
537        match self {
538            Self::Ring(s) => {
539                let additional = window_size.saturating_sub(s.buffer.len());
540                s.buffer.reserve_exact(additional);
541            }
542            Self::Flat(s) => {
543                let additional = window_size.saturating_sub(s.buffer.len());
544                s.buffer.reserve_exact(additional);
545            }
546        }
547    }
548
549    /// Last `n` bytes of the visible buffer as `(s1, s2)` (wrap-aware).
550    /// Routes through whichever backend the current scratch holds.
551    #[cfg(all(feature = "lsm", feature = "hash"))]
552    fn last_n_as_slices(&self, n: usize) -> (&[u8], &[u8]) {
553        match self {
554            Self::Ring(s) => s.buffer.last_n_as_slices(n),
555            Self::Flat(s) => s.buffer.last_n_as_slices(n),
556        }
557    }
558
559    fn buffer_drain(&mut self) -> Vec<u8> {
560        match self {
561            Self::Ring(s) => s.buffer.drain(),
562            Self::Flat(s) => s.buffer.drain(),
563        }
564    }
565
566    fn buffer_drain_to_window_size(&mut self) -> Option<Vec<u8>> {
567        match self {
568            Self::Ring(s) => s.buffer.drain_to_window_size(),
569            Self::Flat(s) => s.buffer.drain_to_window_size(),
570        }
571    }
572
573    fn buffer_drain_to_writer(&mut self, sink: impl Write) -> Result<usize, Error> {
574        match self {
575            Self::Ring(s) => s.buffer.drain_to_writer(sink),
576            Self::Flat(s) => s.buffer.drain_to_writer(sink),
577        }
578    }
579
580    fn buffer_drain_to_window_size_writer(&mut self, sink: impl Write) -> Result<usize, Error> {
581        match self {
582            Self::Ring(s) => s.buffer.drain_to_window_size_writer(sink),
583            Self::Flat(s) => s.buffer.drain_to_window_size_writer(sink),
584        }
585    }
586
587    fn buffer_can_drain(&self) -> usize {
588        match self {
589            Self::Ring(s) => s.buffer.can_drain(),
590            Self::Flat(s) => s.buffer.can_drain(),
591        }
592    }
593
594    fn buffer_can_drain_to_window_size(&self) -> Option<usize> {
595        match self {
596            Self::Ring(s) => s.buffer.can_drain_to_window_size(),
597            Self::Flat(s) => s.buffer.can_drain_to_window_size(),
598        }
599    }
600
601    fn buffer_read(&mut self, target: &mut [u8]) -> Result<usize, Error> {
602        match self {
603            Self::Ring(s) => s.buffer.read(target),
604            Self::Flat(s) => s.buffer.read(target),
605        }
606    }
607
608    fn buffer_read_all(&mut self, target: &mut [u8]) -> Result<usize, Error> {
609        match self {
610            Self::Ring(s) => s.buffer.read_all(target),
611            Self::Flat(s) => s.buffer.read_all(target),
612        }
613    }
614
615    /// Drop visible output beyond `window_size` without producing it,
616    /// keeping the most recent `window_size` bytes available to back
617    /// future match copies. Used by `decode_blocks_partial` to bound
618    /// memory while decoding the leading (skipped) blocks into the window.
619    #[cfg(feature = "lsm")]
620    fn buffer_drop_to_window_size(&mut self) -> usize {
621        match self {
622            Self::Ring(s) => s.buffer.drop_to_window_size(),
623            Self::Flat(s) => s.buffer.drop_to_window_size(),
624        }
625    }
626
627    /// Drop exactly `n` bytes from the front of the visible output without
628    /// producing them. Used by `decode_blocks_partial` to discard the
629    /// leading blocks' window-context bytes once the in-range blocks are
630    /// decoded (match resolution complete), leaving only the in-range output.
631    #[cfg(feature = "lsm")]
632    fn buffer_discard_front(&mut self, n: usize) {
633        match self {
634            Self::Ring(s) => s.buffer.discard_front(n),
635            Self::Flat(s) => s.buffer.discard_front(n),
636        }
637    }
638
639    /// Prime the match window with the caller's already-decompressed tail for
640    /// a resumed partial decode. Routes through whichever backend the current
641    /// scratch holds. See [`DecodeBuffer::prime_window`].
642    #[cfg(feature = "lsm")]
643    fn prime_window(&mut self, prefix: &[u8], total_output: u64) {
644        match self {
645            Self::Ring(s) => s.buffer.prime_window(prefix, total_output),
646            Self::Flat(s) => s.buffer.prime_window(prefix, total_output),
647        }
648    }
649
650    /// Total decompressed bytes produced so far (the buffer's running output
651    /// counter, unaffected by window drops / drains). Used to stamp a captured
652    /// [`ResumeState`]'s `output_offset`.
653    #[cfg(feature = "lsm")]
654    fn total_output(&self) -> u64 {
655        match self {
656            Self::Ring(s) => s.buffer.total_output(),
657            Self::Flat(s) => s.buffer.total_output(),
658        }
659    }
660
661    /// Clone the cross-block entropy/repcode state (FSE + Huffman tables +
662    /// `offset_hist`) out of the live scratch for a [`ResumeState`] snapshot.
663    #[cfg(feature = "lsm")]
664    fn export_entropy(
665        &self,
666        dict: Option<&crate::decoding::dictionary::Dictionary>,
667    ) -> (
668        crate::decoding::scratch::FSEScratch,
669        crate::decoding::scratch::HuffmanScratch,
670        [u32; 3],
671    ) {
672        let (fse_src, huf_src, offset_hist) = match self {
673            Self::Ring(s) => (&s.fse, &s.huf, s.offset_hist),
674            Self::Flat(s) => (&s.fse, &s.huf, s.offset_hist),
675        };
676        // The live scratch may still be `Dict`-sourced; `reinit_from` /
677        // `reinit_resolved_from` resolve those axes through the borrow into a
678        // self-contained `Local` snapshot, so the dictionary is required here
679        // whenever the captured frame is dict-backed.
680        let mut fse = crate::decoding::scratch::FSEScratch::new();
681        fse.reinit_from(fse_src, dict);
682        let mut huf = crate::decoding::scratch::HuffmanScratch::new();
683        huf.reinit_resolved_from(huf_src, dict);
684        (fse, huf, offset_hist)
685    }
686
687    /// Install entropy/repcode state from a [`ResumeState`] into the live
688    /// scratch so a `Repeat_Mode` / treeless resume block resolves against the
689    /// same tables a contiguous decode would have carried over.
690    #[cfg(feature = "lsm")]
691    fn restore_entropy(&mut self, state: &ResumeState) {
692        // The `ResumeState` snapshot is a self-contained `Local` materialization
693        // (export resolved every Dict axis into local bytes and detached), so no
694        // dictionary borrow is needed to install it back.
695        match self {
696            Self::Ring(s) => {
697                s.fse.reinit_from(&state.fse, None);
698                s.huf.reinit_resolved_from(&state.huf, None);
699                s.offset_hist = state.offset_hist;
700            }
701            Self::Flat(s) => {
702                s.fse.reinit_from(&state.fse, None);
703                s.huf.reinit_resolved_from(&state.huf, None);
704                s.offset_hist = state.offset_hist;
705            }
706        }
707    }
708
709    /// XXH64 of the window-prime bytes for a [`ResumeState`]: the last
710    /// `min(window_size, buffer_len)` bytes of the current buffer, which at emit
711    /// time are exactly the match-window context the resume block will see.
712    /// Wrap-aware via `last_n_as_slices` — streaming XXH64 over the two slices
713    /// equals a single hash over the contiguous `window_prime` at resume.
714    #[cfg(all(feature = "lsm", feature = "hash"))]
715    fn window_tail_hash(&self, window_size: usize) -> u64 {
716        use core::hash::Hasher;
717        let n = core::cmp::min(window_size, self.buffer_len());
718        let (s1, s2) = self.last_n_as_slices(n);
719        let mut h = twox_hash::XxHash64::with_seed(0);
720        h.write(s1);
721        h.write(s2);
722        h.finish()
723    }
724
725    fn decode_block_content<R: Read>(
726        &mut self,
727        decoder: &mut BlockDecoder,
728        header: &crate::blocks::block::BlockHeader,
729        source: R,
730        dict: Option<&crate::decoding::dictionary::Dictionary>,
731    ) -> Result<u64, DecodeBlockContentError> {
732        match self {
733            Self::Ring(s) => decoder.decode_block_content(header, s, dict, source),
734            Self::Flat(s) => decoder.decode_block_content(header, s, dict, source),
735        }
736    }
737
738    #[cfg(feature = "hash")]
739    fn hash_finish(&self) -> u64 {
740        use core::hash::Hasher;
741        match self {
742            Self::Ring(s) => s.buffer.hash.finish(),
743            Self::Flat(s) => s.buffer.hash.finish(),
744        }
745    }
746
747    /// Forward the drain-time hash toggle to the inner `DecodeBuffer`
748    /// (streaming path). Called by the frame layer from the decoder's
749    /// `ContentChecksum` mode before each decode.
750    #[cfg(feature = "hash")]
751    fn set_compute_hash(&mut self, compute: bool) {
752        match self {
753            Self::Ring(s) => s.buffer.set_compute_hash(compute),
754            Self::Flat(s) => s.buffer.set_compute_hash(compute),
755        }
756    }
757}
758
759struct FrameDecoderState {
760    pub frame_header: frame::FrameHeader,
761    decoder_scratch: DecoderScratchKind,
762    frame_finished: bool,
763    block_counter: usize,
764    bytes_read_counter: u64,
765    check_sum: Option<u32>,
766    using_dict: Option<u32>,
767    /// The dictionary handle applied to this frame, owned for the frame's whole
768    /// decode so the block loop can hand the scratch a `&Dictionary` borrow at
769    /// every `Dict`-sourced table read. ONE refcount clone per dict-apply (not
770    /// per block, not per frame on the reuse path — the same handle stays held
771    /// across `init_with_dict_handle` -> `decode_blocks`); the decode loop
772    /// borrows from this field (disjoint from `decoder_scratch`) with zero
773    /// further clones. `None` on the no-dict path. Cleared by `reset`.
774    active_dict: Option<DictionaryHandle>,
775}
776
777pub enum BlockDecodingStrategy {
778    All,
779    UptoBlocks(usize),
780    UptoBytes(usize),
781}
782
783/// Outcome of [`FrameDecoder::decode_blocks_partial`]: the decompressed
784/// bytes of the requested inner-block range plus where (if anywhere)
785/// decoding stopped early.
786///
787/// Behind the `lsm` Cargo feature.
788#[cfg(feature = "lsm")]
789#[derive(Debug)]
790pub struct PartialDecode {
791    /// Decompressed bytes of the in-range blocks actually decoded, in
792    /// frame order, as one contiguous buffer. `data.len()` equals the sum
793    /// of the decompressed sizes of blocks `start_block .. start_block +
794    /// blocks_decoded`.
795    pub data: alloc::vec::Vec<u8>,
796    /// First block whose output is in [`data`](Self::data): the requested
797    /// `start_block` on a fresh decode, or [`ResumeState::block_index`] when
798    /// resuming (the caller-supplied `start_block` is ignored in resume mode).
799    pub start_block: u32,
800    /// Number of in-range blocks successfully decoded into
801    /// [`data`](Self::data).
802    pub blocks_decoded: u32,
803    /// `Some((block_index, error))` if decoding stopped on a failing block
804    /// before reaching `end_block` (a corrupt block inside the range, or a
805    /// leading block needed for window context). `None` if the requested
806    /// range decoded cleanly or the frame's last block was reached first.
807    ///
808    /// When the failing block is a leading context block
809    /// (`block_index < start_block`), the in-range window could not be
810    /// built so [`data`](Self::data) is empty and `blocks_decoded` is 0.
811    pub stopped_at: Option<(u32, FrameDecoderError)>,
812    /// `true` if the frame's last block was reached during this decode.
813    pub frame_finished: bool,
814    /// Cross-block carry-over state for resuming the next extent. Feed it back
815    /// (with the matching `window_prime`) via the `resume` argument of a
816    /// later [`FrameDecoder::decode_blocks_partial`] to continue from
817    /// [`ResumeState::block_index`] without re-decompressing the prefix.
818    ///
819    /// `None` in two cases: emission was not requested (`emit_resume = false`),
820    /// OR this decode reached the frame's last block ([`frame_finished`] is
821    /// `true`) — there is no following block to resume from, so no snapshot is
822    /// emitted even with `emit_resume = true`. Callers walking a frame
823    /// incrementally should therefore stop when `frame_finished` is set rather
824    /// than treat a `None` here as "emission disabled".
825    ///
826    /// [`frame_finished`]: Self::frame_finished
827    pub resume_state: Option<ResumeState>,
828}
829
830impl FrameDecoderState {
831    /// Window size to actually reserve for this frame's decode buffer.
832    /// A declared content size caps the useful window: matches can never
833    /// reference further back than the bytes that will ever exist, so an
834    /// encoder-declared window above the FCS (e.g. a level-preset window
835    /// on a smaller input) must not inflate the reservation. Every
836    /// `reserve_buffer` site routes through this so the cap is uniform
837    /// across `decode_all_impl`, `decode_blocks`, and the partial path.
838    fn useful_window_size(&self) -> usize {
839        let window_size = self.frame_header.window_size().unwrap_or(0);
840        if self.frame_header.fcs_declared() {
841            window_size.min(self.frame_header.frame_content_size()) as usize
842        } else {
843            window_size as usize
844        }
845    }
846
847    /// Construct a new frame decoder state, reading the frame header
848    /// from `source`. When `magicless` is `true`, the 4-byte magic
849    /// number prefix is NOT consumed (upstream zstd `ZSTD_f_zstd1_magicless`).
850    /// Crate-internal — reached only via `FrameDecoder::init` /
851    /// `FrameDecoder::init_with_dict_handle`. The decode buffer is
852    /// allocated lazily on BOTH backends (`new_ring` and `new_flat`):
853    /// direct-eligible frames pay zero buffer allocation, and the
854    /// non-direct fallback reserves `window_size` once in
855    /// `decode_all_impl` / `decode_blocks` via `reserve_buffer` before
856    /// any block write.
857    #[inline]
858    pub(crate) fn new_with_format(
859        source: impl Read,
860        magicless: bool,
861    ) -> Result<FrameDecoderState, FrameDecoderError> {
862        let (frame, header_size) = frame::read_frame_header_with_format(source, magicless)?;
863        let window_size = frame.window_size()?;
864
865        if window_size > MAXIMUM_ALLOWED_WINDOW_SIZE {
866            return Err(FrameDecoderError::WindowSizeTooBig {
867                requested: window_size,
868            });
869        }
870
871        let decoder_scratch = if frame.descriptor.single_segment_flag() {
872            DecoderScratchKind::new_flat(window_size as usize)
873        } else {
874            DecoderScratchKind::new_ring(window_size as usize)
875        };
876        Ok(FrameDecoderState {
877            frame_header: frame,
878            frame_finished: false,
879            block_counter: 0,
880            decoder_scratch,
881            bytes_read_counter: u64::from(header_size),
882            check_sum: None,
883            using_dict: None,
884            active_dict: None,
885        })
886    }
887
888    /// Reset this state for a new frame read from `source`, reusing
889    /// existing allocations. When `magicless` is `true`, the frame
890    /// header is read WITHOUT expecting a magic-number prefix
891    /// (upstream zstd `ZSTD_f_zstd1_magicless`). Crate-internal — reached
892    /// only via `FrameDecoder::reset`.
893    ///
894    /// `DecodeBuffer::reset` no longer reserves window_size for either
895    /// backend — capacity decisions live one layer up. Both backends are
896    /// lazy: direct-eligible frames pay zero backing-buffer allocation
897    /// here (they write through `UserSliceBackend`), and the non-direct
898    /// path is pre-reserved by `decode_all_impl` / `decode_blocks` via
899    /// `DecoderScratchKind::reserve_buffer(window_size)` before any block
900    /// write. A reused scratch whose new frame fits within prior capacity
901    /// reuses it; a larger one grows on that same `reserve_buffer` call.
902    #[inline]
903    pub(crate) fn reset_with_format(
904        &mut self,
905        source: impl Read,
906        magicless: bool,
907    ) -> Result<(), FrameDecoderError> {
908        let (frame_header, header_size) = frame::read_frame_header_with_format(source, magicless)?;
909        let window_size = frame_header.window_size()?;
910
911        if window_size > MAXIMUM_ALLOWED_WINDOW_SIZE {
912            return Err(FrameDecoderError::WindowSizeTooBig {
913                requested: window_size,
914            });
915        }
916
917        self.decoder_scratch
918            .reset(&frame_header, window_size as usize);
919        self.frame_header = frame_header;
920        self.frame_finished = false;
921        self.block_counter = 0;
922        self.bytes_read_counter = u64::from(header_size);
923        self.check_sum = None;
924        self.using_dict = None;
925        // `active_dict` is intentionally NOT cleared here: it is only ever READ
926        // while a scratch table source is `Dict`, which `init_from_dict` arms
927        // on a dict frame and which a no-dict frame leaves `Local` (so a stale
928        // held handle is never read). Keeping it lets the per-apply `ptr::eq`
929        // reuse-check below skip the clone when the SAME dictionary is
930        // re-applied frame-over-frame (the CoordiNode per-label-dict hot path)
931        // — zero refcount churn on reuse, one clone only on a genuine swap.
932        Ok(())
933    }
934
935    /// Hold the dictionary handle for this frame's whole decode so the block
936    /// loop can borrow `&Dictionary` at every `Dict`-sourced read. Clones the
937    /// handle ONLY when it is a different dictionary than the one already held
938    /// (`ptr::eq` on the `Arc`'s pointee) — so re-applying the SAME dictionary
939    /// frame-over-frame (the reuse hot path) costs zero refcount churn.
940    fn set_active_dict(&mut self, dict: &DictionaryHandle) {
941        if self
942            .active_dict
943            .as_ref()
944            .is_none_or(|held| !core::ptr::eq(held.as_dict(), dict.as_dict()))
945        {
946            self.active_dict = Some(dict.clone());
947        }
948    }
949}
950
951impl Default for FrameDecoder {
952    fn default() -> Self {
953        Self::new()
954    }
955}
956
957impl FrameDecoder {
958    /// This will create a new decoder without allocating anything yet.
959    /// init()/reset() will allocate all needed buffers if it is the first time this decoder is used
960    /// else they just reset these buffers with not further allocations
961    pub fn new() -> FrameDecoder {
962        FrameDecoder {
963            state: None,
964            #[cfg(test)]
965            direct_frames: 0,
966            owned_dicts: BTreeMap::new(),
967            #[cfg(target_has_atomic = "ptr")]
968            shared_dicts: BTreeMap::new(),
969            #[cfg(not(target_has_atomic = "ptr"))]
970            shared_dicts: (),
971            magicless: false,
972            content_checksum: ContentChecksum::EmitOnly,
973            #[cfg(feature = "lsm")]
974            expect_dict_id: None,
975            #[cfg(feature = "lsm")]
976            expect_window_descriptor: None,
977            #[cfg(all(feature = "lsm", feature = "hash"))]
978            per_block_checksums_enabled: false,
979            #[cfg(all(feature = "lsm", feature = "hash"))]
980            computed_block_checksums: alloc::vec::Vec::new(),
981        }
982    }
983
984    /// Heap bytes currently held by the decoder's lazily-grown workspace:
985    /// the decode-window buffer plus the per-block literal/content buffers
986    /// and the entropy tables. Returns 0 before the first frame is initialised
987    /// (no workspace allocated yet). The window allocation dominates and grows
988    /// with the frame's window size; this is the value to track for decode-time
989    /// memory pressure, mirroring the workspace term of upstream
990    /// `ZSTD_sizeof_DCtx`. Shared dictionaries (ref-counted handles) are not
991    /// counted, matching upstream excluding `refDDict` memory.
992    pub fn workspace_size(&self) -> usize {
993        self.state
994            .as_ref()
995            .map_or(0, |s| s.decoder_scratch.workspace_bytes())
996    }
997
998    /// Select how the frame's optional content checksum is handled
999    /// (compute, expose, verify, or skip). See [`ContentChecksum`].
1000    /// Default [`ContentChecksum::EmitOnly`]. Takes effect on the next
1001    /// decode; safe to call between frames on a reused decoder.
1002    pub fn set_content_checksum(&mut self, mode: ContentChecksum) {
1003        self.content_checksum = mode;
1004    }
1005
1006    /// Opt in to per-block XXH64 verification during decode.
1007    /// Default off; zero cost when disabled. Each block's decompressed
1008    /// bytes are XXH64-hashed (low 32 bits) and appended to
1009    /// [`Self::computed_block_checksums`] as the decode progresses.
1010    /// Callers compare the captured digests against externally-stored
1011    /// expected values (e.g. from a per-block sidecar in the
1012    /// containing application protocol).
1013    ///
1014    /// Behind `all(feature = "lsm", feature = "hash")` — the XXH64
1015    /// primitive lives behind the `hash` feature, so this method
1016    /// only compiles when both are enabled.
1017    #[cfg(all(feature = "lsm", feature = "hash"))]
1018    pub fn enable_per_block_checksums(&mut self) {
1019        self.per_block_checksums_enabled = true;
1020    }
1021
1022    /// Per-block XXH64 (low 32 bits) digests captured during the
1023    /// current frame's decode. Empty unless
1024    /// [`Self::enable_per_block_checksums`] was called before
1025    /// [`Self::decode_all`] / [`Self::reset`].
1026    ///
1027    /// Reset at the start of every new frame.
1028    ///
1029    /// Behind `all(feature = "lsm", feature = "hash")`.
1030    #[cfg(all(feature = "lsm", feature = "hash"))]
1031    pub fn computed_block_checksums(&self) -> &[u32] {
1032        &self.computed_block_checksums
1033    }
1034
1035    /// Pin the expected `Dictionary_ID` for the next frame.
1036    ///
1037    /// When `expected` is set, [`Self::init`] / [`Self::reset`]
1038    /// validate it against the parsed frame header BEFORE any
1039    /// block decode work runs. A mismatch returns
1040    /// [`crate::decoding::errors::FrameDecoderError::UnexpectedDictId`]
1041    /// before any block decode and before any output is produced.
1042    /// Scratch buffer allocation / reservation for the decode
1043    /// pipeline happens during frame-header parsing, which is
1044    /// already complete when this validation fires — the cost of
1045    /// scratch sizing is paid even on a mismatched header. The
1046    /// guarantee is "no block decode, no XXH64 init, no partial
1047    /// output", not "zero allocation".
1048    ///
1049    /// `Some(0)` is treated as "no dictionary expected": a frame
1050    /// whose header omits the optional `Dictionary_ID` field
1051    /// (flag value 0) passes the check; a frame that carries an
1052    /// explicit non-zero id fails.
1053    ///
1054    /// `None` (default) disables the check.
1055    ///
1056    /// Primary use case: post-AEAD-decrypt sanity check in
1057    /// wire-format consumers (e.g. lsm-tree's encrypted block
1058    /// format pins the `dict_id` baked into the AAD against the
1059    /// inner zstd frame's `dict_id` to defeat dict-substitution
1060    /// attacks).
1061    ///
1062    /// NOT a replacement for AEAD authentication. NOT the same
1063    /// semantic as upstream zstd `ZSTD_d_windowLogMax` (which is a
1064    /// ceiling-style limit, separate concern).
1065    #[cfg(feature = "lsm")]
1066    #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
1067    pub fn expect_dict_id(&mut self, expected: Option<u32>) {
1068        self.expect_dict_id = expected;
1069    }
1070
1071    /// Pin the expected raw `Window_Descriptor` byte (RFC 8878
1072    /// §3.1.1.1.2 layout: `(exp << 3) | mantissa`) for the next
1073    /// frame.
1074    ///
1075    /// When `expected` is set, [`Self::init`] / [`Self::reset`]
1076    /// validate it against the parsed frame header BEFORE any
1077    /// block decode work runs. A mismatch returns
1078    /// [`crate::decoding::errors::FrameDecoderError::UnexpectedWindowDescriptor`].
1079    ///
1080    /// Single-segment frames omit the `Window_Descriptor` byte
1081    /// from the wire entirely. Setting an expectation while
1082    /// receiving a single-segment frame fails the check with
1083    /// `found: None` — there is no on-wire byte to match against,
1084    /// which is reported explicitly rather than silently passing.
1085    ///
1086    /// `None` (default) disables the check.
1087    ///
1088    /// Byte-exact equality, NOT a ceiling. Upstream zstd
1089    /// `ZSTD_d_windowLogMax` is a separate ceiling-style limit
1090    /// available through the C FFI surface; this method is for
1091    /// strict equality validation against a pinned expectation
1092    /// (e.g. lsm-tree's wire format pins the window descriptor
1093    /// from the AAD to defeat decompression-bomb-swap attacks).
1094    #[cfg(feature = "lsm")]
1095    #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
1096    pub fn expect_window_descriptor(&mut self, expected: Option<u8>) {
1097        self.expect_window_descriptor = expected;
1098    }
1099
1100    /// Validate the just-parsed frame header against any pinned
1101    /// expectations set via [`Self::expect_dict_id`] /
1102    /// [`Self::expect_window_descriptor`].
1103    ///
1104    /// Returns the typed error variant on mismatch and leaves
1105    /// `self.state` in a re-resettable shape — a subsequent
1106    /// `reset()` will overwrite `frame_header` from the new source
1107    /// without needing intermediate cleanup.
1108    #[cfg(feature = "lsm")]
1109    fn validate_expectations(
1110        &self,
1111        frame_header: &frame::FrameHeader,
1112    ) -> Result<(), FrameDecoderError> {
1113        if let Some(expected) = self.expect_dict_id {
1114            let found = frame_header.dictionary_id();
1115            // `Some(0)` is the "no dictionary expected" sentinel —
1116            // matches a frame whose header omits the optional
1117            // dict_id field (which is reported as `None` by the
1118            // parser). All other values must match exactly.
1119            let matches = match (expected, found) {
1120                (0, None) => true,
1121                (e, Some(f)) => e == f,
1122                _ => false,
1123            };
1124            if !matches {
1125                return Err(FrameDecoderError::UnexpectedDictId {
1126                    expected: Some(expected),
1127                    found,
1128                });
1129            }
1130        }
1131        if let Some(expected) = self.expect_window_descriptor {
1132            let found = frame_header.window_descriptor();
1133            if found != Some(expected) {
1134                return Err(FrameDecoderError::UnexpectedWindowDescriptor { expected, found });
1135            }
1136        }
1137        Ok(())
1138    }
1139
1140    /// Enable or disable magicless frame format
1141    /// (`ZSTD_f_zstd1_magicless`). When set to `true`, subsequent
1142    /// [`init`] / [`reset`] calls expect the frame header to begin
1143    /// directly with the frame-header descriptor — no 4-byte magic
1144    /// number prefix. Default false. Must match the encoder's
1145    /// magicless setting; the format is unambiguous only when the
1146    /// caller knows it out-of-band.
1147    ///
1148    /// Note: magicless mode also disables skippable-frame detection.
1149    /// The `0x184D2A50..=0x184D2A5F` skippable-frame magic range is
1150    /// only recognised when the 4-byte magic prefix is consumed, so
1151    /// `decode_all` / `init` / `reset` will treat a skippable frame
1152    /// at the head of a magicless stream as a malformed frame header
1153    /// (bad descriptor / window-size error) instead of skipping it.
1154    /// Mixed-format streams that interleave skippable frames must be
1155    /// pre-split by the caller; `set_magicless(true)` is only safe
1156    /// when the entire stream is known to be magicless zstd frames.
1157    pub fn set_magicless(&mut self, magicless: bool) {
1158        self.magicless = magicless;
1159    }
1160
1161    #[cfg(target_has_atomic = "ptr")]
1162    fn shared_dict_exists(&self, dict_id: u32) -> bool {
1163        self.shared_dicts.contains_key(&dict_id)
1164    }
1165
1166    #[cfg(not(target_has_atomic = "ptr"))]
1167    fn shared_dict_exists(&self, _dict_id: u32) -> bool {
1168        false
1169    }
1170
1171    fn validate_registered_dictionary(dict: &Dictionary) -> Result<(), FrameDecoderError> {
1172        use crate::decoding::errors::DictionaryDecodeError as dict_err;
1173
1174        if dict.id == 0 {
1175            return Err(FrameDecoderError::from(dict_err::ZeroDictionaryId));
1176        }
1177        if let Some(index) = dict.offset_hist.iter().position(|&rep| rep == 0) {
1178            return Err(FrameDecoderError::from(
1179                dict_err::ZeroRepeatOffsetInDictionary { index: index as u8 },
1180            ));
1181        }
1182        Ok(())
1183    }
1184
1185    /// init() will allocate all needed buffers if it is the first time this decoder is used
1186    /// else they just reset these buffers with not further allocations
1187    ///
1188    /// Note that all bytes currently in the decodebuffer from any previous frame will be lost. Collect them with collect()/collect_to_writer()
1189    ///
1190    /// equivalent to reset()
1191    #[inline]
1192    pub fn init(&mut self, source: impl Read) -> Result<(), FrameDecoderError> {
1193        self.reset(source)
1194    }
1195
1196    /// Initialize the decoder for a new frame using a pre-parsed dictionary handle.
1197    ///
1198    /// If the frame header has a dictionary ID, this validates it against
1199    /// `dict.id()` and returns [`FrameDecoderError::DictIdMismatch`] on mismatch.
1200    ///
1201    /// If the header omits the optional dictionary ID, this still applies the
1202    /// provided dictionary handle.
1203    ///
1204    /// # Warning
1205    ///
1206    /// This method always applies `dict` unless the frame header contains a
1207    /// non-matching dictionary ID. Callers must only use this API when they
1208    /// already know the frame was encoded with the provided dictionary, even if
1209    /// the frame header omits the dictionary ID or encodes an explicit
1210    /// dictionary ID of `0`.
1211    ///
1212    /// Passing a dictionary for a frame that was not encoded with it can
1213    /// silently corrupt the decoded output.
1214    pub fn init_with_dict_handle(
1215        &mut self,
1216        source: impl Read,
1217        dict: &DictionaryHandle,
1218    ) -> Result<(), FrameDecoderError> {
1219        self.reset_with_dict_handle(source, dict)
1220    }
1221
1222    /// reset() will allocate all needed buffers if it is the first time this decoder is used
1223    /// else they just reset these buffers with not further allocations
1224    ///
1225    /// Note that all bytes currently in the decodebuffer from any previous frame will be lost. Collect them with collect()/collect_to_writer()
1226    ///
1227    /// equivalent to init()
1228    #[inline]
1229    pub fn reset(&mut self, source: impl Read) -> Result<(), FrameDecoderError> {
1230        use FrameDecoderError as err;
1231        // Fresh frame → start with an empty per-block checksum vec so
1232        // the values for the next frame don't carry over from the
1233        // previous one.
1234        #[cfg(all(feature = "lsm", feature = "hash"))]
1235        self.computed_block_checksums.clear();
1236        let magicless = self.magicless;
1237        let dict_id = match &mut self.state {
1238            Some(s) => {
1239                s.reset_with_format(source, magicless)?;
1240                s.frame_header.dictionary_id()
1241            }
1242            None => {
1243                self.state = Some(FrameDecoderState::new_with_format(source, magicless)?);
1244                self.state
1245                    .as_ref()
1246                    .and_then(|state| state.frame_header.dictionary_id())
1247            }
1248        };
1249        // Validate any pinned expectations BEFORE block decode work
1250        // runs. Catches dict_id substitution / window-descriptor
1251        // tampering on inputs already authenticated by an outer
1252        // layer (e.g. AEAD). Returning here leaves `self.state` in
1253        // a re-resettable shape — next `reset()` re-parses the
1254        // frame header without intermediate cleanup.
1255        #[cfg(feature = "lsm")]
1256        if let Some(state) = self.state.as_ref() {
1257            self.validate_expectations(&state.frame_header)?;
1258        }
1259        if let Some(dict_id) = dict_id {
1260            let state = self.state.as_mut().expect("state initialized");
1261            let owned_dicts = &self.owned_dicts;
1262            #[cfg(target_has_atomic = "ptr")]
1263            let shared_dicts = &self.shared_dicts;
1264            let dict = owned_dicts
1265                .get(&dict_id)
1266                .or_else(|| {
1267                    #[cfg(target_has_atomic = "ptr")]
1268                    {
1269                        shared_dicts.get(&dict_id)
1270                    }
1271                    #[cfg(not(target_has_atomic = "ptr"))]
1272                    {
1273                        None
1274                    }
1275                })
1276                .ok_or(err::DictNotProvided { dict_id })?;
1277            state.decoder_scratch.init_from_dict(dict);
1278            state.set_active_dict(dict);
1279            state.using_dict = Some(dict_id);
1280        }
1281        Ok(())
1282    }
1283
1284    /// Reset this decoder for a new frame using a pre-parsed dictionary handle.
1285    ///
1286    /// If the frame header has a dictionary ID, this validates it against
1287    /// `dict.id()` and returns [`FrameDecoderError::DictIdMismatch`] on mismatch.
1288    ///
1289    /// If the header omits the optional dictionary ID, this still applies the
1290    /// provided dictionary handle.
1291    ///
1292    /// # Warning
1293    ///
1294    /// This method always applies `dict` unless the frame header contains a
1295    /// non-matching dictionary ID. Callers must only use this API when they
1296    /// already know the frame was encoded with the provided dictionary, even if
1297    /// the frame header omits the dictionary ID or encodes an explicit
1298    /// dictionary ID of `0`.
1299    ///
1300    /// Passing a dictionary for a frame that was not encoded with it can
1301    /// silently corrupt the decoded output.
1302    pub fn reset_with_dict_handle(
1303        &mut self,
1304        source: impl Read,
1305        dict: &DictionaryHandle,
1306    ) -> Result<(), FrameDecoderError> {
1307        use FrameDecoderError as err;
1308        // Fresh frame → drop the previous frame's per-block checksum
1309        // digests so the next decode starts with an empty vec.
1310        // Mirrors the same clear in `reset()`; reset_with_dict_handle
1311        // is a parallel entry point so it needs its own call.
1312        #[cfg(all(feature = "lsm", feature = "hash"))]
1313        self.computed_block_checksums.clear();
1314        Self::validate_registered_dictionary(dict.as_dict())?;
1315        let magicless = self.magicless;
1316        // Scope the &mut borrow of `self.state` to the header parse
1317        // alone, so the subsequent `validate_expectations(&self, ...)`
1318        // call below can take a fresh shared borrow of self without
1319        // tripping the borrow checker.
1320        match &mut self.state {
1321            Some(s) => s.reset_with_format(source, magicless)?,
1322            None => {
1323                self.state = Some(FrameDecoderState::new_with_format(source, magicless)?);
1324            }
1325        }
1326        // Single source of truth: route through the same
1327        // `validate_expectations` used by `reset()`. Routing through
1328        // the helper keeps the two code paths from drifting (e.g.,
1329        // if expect-semantics or error wiring changes later).
1330        #[cfg(feature = "lsm")]
1331        {
1332            let header = &self
1333                .state
1334                .as_ref()
1335                .expect("state populated by reset_with_format/new_with_format")
1336                .frame_header;
1337            self.validate_expectations(header)?;
1338        }
1339        let state = self
1340            .state
1341            .as_mut()
1342            .expect("state populated by reset_with_format/new_with_format");
1343        if let Some(dict_id) = state.frame_header.dictionary_id()
1344            && dict_id != dict.id()
1345        {
1346            return Err(err::DictIdMismatch {
1347                expected: dict_id,
1348                provided: dict.id(),
1349            });
1350        }
1351        state.decoder_scratch.init_from_dict(dict);
1352        state.set_active_dict(dict);
1353        state.using_dict = Some(dict.id());
1354        Ok(())
1355    }
1356
1357    /// Add a dictionary that can be selected dynamically by frame dictionary ID.
1358    ///
1359    /// Returns [`FrameDecoderError::DictAlreadyRegistered`] if the ID is already
1360    /// registered (either as owned or shared).
1361    pub fn add_dict(&mut self, dict: Dictionary) -> Result<(), FrameDecoderError> {
1362        Self::validate_registered_dictionary(&dict)?;
1363        let dict_id = dict.id;
1364        if self.owned_dicts.contains_key(&dict_id) || self.shared_dict_exists(dict_id) {
1365            return Err(FrameDecoderError::DictAlreadyRegistered { dict_id });
1366        }
1367        self.owned_dicts
1368            .insert(dict_id, DictionaryHandle::from_dictionary(dict));
1369        Ok(())
1370    }
1371
1372    /// Parse and add a serialized dictionary blob.
1373    pub fn add_dict_from_bytes(&mut self, raw_dictionary: &[u8]) -> Result<(), FrameDecoderError> {
1374        let dict = Dictionary::decode_dict(raw_dictionary)?;
1375        self.add_dict(dict)
1376    }
1377
1378    /// Add a pre-parsed dictionary handle for reuse across decoders.
1379    ///
1380    /// This API is available on targets with pointer-width atomics
1381    /// (`target_has_atomic = "ptr"`).
1382    ///
1383    /// Returns [`FrameDecoderError::DictAlreadyRegistered`] if the ID is already
1384    /// registered (either as owned or shared).
1385    #[cfg(target_has_atomic = "ptr")]
1386    pub fn add_dict_handle(&mut self, dict: DictionaryHandle) -> Result<(), FrameDecoderError> {
1387        Self::validate_registered_dictionary(dict.as_dict())?;
1388        let dict_id = dict.id();
1389        if self.owned_dicts.contains_key(&dict_id) || self.shared_dicts.contains_key(&dict_id) {
1390            return Err(FrameDecoderError::DictAlreadyRegistered { dict_id });
1391        }
1392        self.shared_dicts.insert(dict_id, dict);
1393        Ok(())
1394    }
1395
1396    pub fn force_dict(&mut self, dict_id: u32) -> Result<(), FrameDecoderError> {
1397        use FrameDecoderError as err;
1398        let state = self.state.as_mut().ok_or(err::NotYetInitialized)?;
1399        let owned_dicts = &self.owned_dicts;
1400        #[cfg(target_has_atomic = "ptr")]
1401        let shared_dicts = &self.shared_dicts;
1402
1403        let dict = owned_dicts
1404            .get(&dict_id)
1405            .or_else(|| {
1406                #[cfg(target_has_atomic = "ptr")]
1407                {
1408                    shared_dicts.get(&dict_id)
1409                }
1410                #[cfg(not(target_has_atomic = "ptr"))]
1411                {
1412                    None
1413                }
1414            })
1415            .ok_or(err::DictNotProvided { dict_id })?;
1416        state.decoder_scratch.init_from_dict(dict);
1417        state.set_active_dict(dict);
1418        state.using_dict = Some(dict_id);
1419
1420        Ok(())
1421    }
1422
1423    /// Returns how many bytes the frame contains after decompression
1424    pub fn content_size(&self) -> u64 {
1425        match &self.state {
1426            None => 0,
1427            Some(s) => s.frame_header.frame_content_size(),
1428        }
1429    }
1430
1431    /// Returns the checksum that was read from the data. Only available after all bytes have been read. It is the last 4 bytes of a zstd-frame
1432    pub fn get_checksum_from_data(&self) -> Option<u32> {
1433        let state = self.state.as_ref()?;
1434
1435        state.check_sum
1436    }
1437
1438    /// Returns the checksum that was calculated while decoding.
1439    /// Only a sensible value after all decoded bytes have been collected/read from the FrameDecoder.
1440    /// Returns `None` when the frame header has `content_checksum_flag = 0`:
1441    /// no hash is computed for such frames (the post-decode XXH64 pass was a
1442    /// 63 % decode-wall hotspot on flag-off frames; skipping it when the
1443    /// frame format declares no trailing digest avoids that wasted work).
1444    #[cfg(feature = "hash")]
1445    pub fn get_calculated_checksum(&self) -> Option<u32> {
1446        let state = self.state.as_ref()?;
1447        // `ContentChecksum::None` skips the XXH64 pass entirely, so there is
1448        // no calculated digest to report.
1449        if self.content_checksum == ContentChecksum::None {
1450            return None;
1451        }
1452        if !state.frame_header.descriptor.content_checksum_flag() {
1453            return None;
1454        }
1455        let cksum_64bit = state.decoder_scratch.hash_finish();
1456        //truncate to lower 32bit because reasons...
1457        Some(cksum_64bit as u32)
1458    }
1459
1460    /// Compare the frame's stored content checksum against the digest the
1461    /// decoder computed, returning [`FrameDecoderError::ChecksumMismatch`] on
1462    /// disagreement. No-op unless the mode is [`ContentChecksum::Verify`] and
1463    /// the frame carries a trailing checksum.
1464    ///
1465    /// [`decode_all`](Self::decode_all) and the streaming reader call this
1466    /// automatically. Callers driving [`decode_blocks`](Self::decode_blocks)
1467    /// directly invoke it themselves once per frame, after the frame is fully
1468    /// decoded AND fully drained (e.g. via [`collect`](Self::collect)), so both
1469    /// the stored value and the running digest are final.
1470    #[cfg(feature = "hash")]
1471    pub fn verify_content_checksum(&self) -> Result<(), FrameDecoderError> {
1472        if self.content_checksum != ContentChecksum::Verify {
1473            return Ok(());
1474        }
1475        let Some(state) = self.state.as_ref() else {
1476            return Ok(());
1477        };
1478        if !state.frame_header.descriptor.content_checksum_flag() {
1479            return Ok(());
1480        }
1481        let Some(expected) = state.check_sum else {
1482            return Ok(());
1483        };
1484        let calculated = state.decoder_scratch.hash_finish() as u32;
1485        if expected != calculated {
1486            return Err(FrameDecoderError::ChecksumMismatch {
1487                expected,
1488                calculated,
1489            });
1490        }
1491        Ok(())
1492    }
1493
1494    /// Counter for how many bytes have been consumed while decoding the frame
1495    pub fn bytes_read_from_source(&self) -> u64 {
1496        let state = match &self.state {
1497            None => return 0,
1498            Some(s) => s,
1499        };
1500        state.bytes_read_counter
1501    }
1502
1503    /// Test-only: number of frames decoded through the single-copy direct
1504    /// path (`run_direct_decode`). Lets cross-module tests assert that a
1505    /// given decode took the decode-in-place path rather than the ring drain.
1506    #[cfg(test)]
1507    pub(crate) fn direct_frames(&self) -> u64 {
1508        self.direct_frames
1509    }
1510
1511    /// Test-only: whether the decode state currently holds an owning dictionary
1512    /// handle (`active_dict`). Every path that arms `Dict`-sourced scratch tables
1513    /// must also install this handle, or a later dict-table read resolves `None`.
1514    #[cfg(test)]
1515    pub(crate) fn active_dict_installed(&self) -> bool {
1516        self.state.as_ref().is_some_and(|s| s.active_dict.is_some())
1517    }
1518
1519    /// Whether the current frames last block has been decoded yet
1520    /// If this returns true you can call the drain* functions to get all content
1521    /// (the read() function will drain automatically if this returns true)
1522    pub fn is_finished(&self) -> bool {
1523        let state = match &self.state {
1524            None => return true,
1525            Some(s) => s,
1526        };
1527        if state.frame_header.descriptor.content_checksum_flag() {
1528            state.frame_finished && state.check_sum.is_some()
1529        } else {
1530            state.frame_finished
1531        }
1532    }
1533
1534    /// Counter for how many blocks have already been decoded
1535    pub fn blocks_decoded(&self) -> usize {
1536        let state = match &self.state {
1537            None => return 0,
1538            Some(s) => s,
1539        };
1540        state.block_counter
1541    }
1542
1543    /// Decodes blocks from a reader. It requires that the framedecoder has been initialized first.
1544    /// The Strategy influences how many blocks will be decoded before the function returns
1545    /// This is important if you want to manage memory consumption carefully. If you don't care
1546    /// about that you can just choose the strategy "All" and have all blocks of the frame decoded into the buffer
1547    pub fn decode_blocks(
1548        &mut self,
1549        mut source: impl Read,
1550        strat: BlockDecodingStrategy,
1551    ) -> Result<bool, FrameDecoderError> {
1552        use FrameDecoderError as err;
1553        // Apply the content-checksum mode to the streaming drain hash before
1554        // any block decodes into the ring. Hash only when a digest is both
1555        // wanted (mode != None) AND present in the frame (content_checksum_flag
1556        // set) — a flag-off frame has nothing to verify or expose, so hashing
1557        // it is wasted work. Mirrors the direct path and get_calculated_checksum.
1558        #[cfg(feature = "hash")]
1559        let checksum_mode = self.content_checksum;
1560        let state = self.state.as_mut().ok_or(err::NotYetInitialized)?;
1561        #[cfg(feature = "hash")]
1562        {
1563            let compute_hash = checksum_mode != ContentChecksum::None
1564                && state.frame_header.descriptor.content_checksum_flag();
1565            state.decoder_scratch.set_compute_hash(compute_hash);
1566        }
1567
1568        // Streaming entry point: pre-reserve the backing buffer to
1569        // the FCS-capped window so multi-block frames don't pay repeated
1570        // `reserve_amortized` grow steps (128 KiB → 256 KiB → ... →
1571        // window) as blocks accumulate. `decode_all` does the same up
1572        // front in `decode_all_impl`; this mirrors it for callers
1573        // driving `decode_blocks` directly. Idempotent — the
1574        // backend's `reserve` early-returns when capacity is already
1575        // sufficient.
1576        let useful_window = state.useful_window_size();
1577        state.decoder_scratch.reserve_buffer(useful_window);
1578
1579        let mut block_dec = decoding::block_decoder::new();
1580
1581        let buffer_size_before = state.decoder_scratch.buffer_len();
1582        let block_counter_before = state.block_counter;
1583        loop {
1584            vprintln!("################");
1585            vprintln!("Next Block: {}", state.block_counter);
1586            vprintln!("################");
1587            // Capture the failing-block coordinates BEFORE the header read so
1588            // the error carries where it happened: `bytes_read_counter` is the
1589            // frame-absolute offset of this block's header (not yet advanced),
1590            // `block_counter` its 0-based index. Used by both the header- and
1591            // body-error builders below (block-precise recovery under `lsm`).
1592            let block_index = state.block_counter as u32;
1593            let block_frame_offset = state.bytes_read_counter as u32;
1594            let (block_header, block_header_size) =
1595                block_dec.read_block_header(&mut source).map_err(|source| {
1596                    block_header_decode_error(source, block_index, block_frame_offset)
1597                })?;
1598            state.bytes_read_counter += u64::from(block_header_size);
1599
1600            vprintln!();
1601            vprintln!(
1602                "Found {} block with size: {}, which will be of size: {}",
1603                block_header.block_type,
1604                block_header.content_size,
1605                block_header.decompressed_size
1606            );
1607
1608            #[cfg(all(feature = "lsm", feature = "hash"))]
1609            let len_before_block: Option<usize> = if self.per_block_checksums_enabled {
1610                Some(state.decoder_scratch.buffer_len())
1611            } else {
1612                None
1613            };
1614            // Only expose the held dictionary while THIS frame is dict-backed
1615            // (`using_dict` is set per dict-apply, cleared on reset). A reused
1616            // decoder keeps `active_dict` across a no-dict frame for the
1617            // `ptr::eq` reuse-skip, so it must be gated here or a stray
1618            // out-of-window offset on a dictless frame would resolve against the
1619            // stale dictionary content instead of erroring.
1620            let dict_ref = if state.using_dict.is_some() {
1621                state.active_dict.as_ref().map(|h| h.as_dict())
1622            } else {
1623                None
1624            };
1625            let bytes_read_in_block_body = state
1626                .decoder_scratch
1627                .decode_block_content(&mut block_dec, &block_header, &mut source, dict_ref)
1628                .map_err(|source| {
1629                    block_body_decode_error(
1630                        source,
1631                        block_index,
1632                        block_frame_offset,
1633                        &block_header,
1634                        block_header_size,
1635                    )
1636                })?;
1637            state.bytes_read_counter += bytes_read_in_block_body;
1638
1639            // Per-block XXH64 (low 32 bits) of the just-decompressed
1640            // bytes. Hashed from `last_n_as_slices` so RingBuffer wrap
1641            // is handled in-place, no extra copy.
1642            #[cfg(all(feature = "lsm", feature = "hash"))]
1643            if let Some(len_before_block) = len_before_block {
1644                let added = state.decoder_scratch.buffer_len() - len_before_block;
1645                let (s1, s2) = state.decoder_scratch.last_n_as_slices(added);
1646                let mut h = twox_hash::XxHash64::with_seed(0);
1647                use core::hash::Hasher;
1648                h.write(s1);
1649                h.write(s2);
1650                self.computed_block_checksums.push(h.finish() as u32);
1651            }
1652
1653            state.block_counter += 1;
1654
1655            vprintln!("Output: {}", state.decoder_scratch.buffer_len());
1656
1657            if block_header.last_block {
1658                state.frame_finished = true;
1659                if state.frame_header.descriptor.content_checksum_flag() {
1660                    let mut chksum = [0u8; 4];
1661                    source
1662                        .read_exact(&mut chksum)
1663                        .map_err(err::FailedToReadChecksum)?;
1664                    state.bytes_read_counter += 4;
1665                    let chksum = u32::from_le_bytes(chksum);
1666                    state.check_sum = Some(chksum);
1667                }
1668                break;
1669            }
1670
1671            match strat {
1672                BlockDecodingStrategy::All => { /* keep going */ }
1673                BlockDecodingStrategy::UptoBlocks(n) => {
1674                    if state.block_counter - block_counter_before >= n {
1675                        break;
1676                    }
1677                }
1678                BlockDecodingStrategy::UptoBytes(n) => {
1679                    if state.decoder_scratch.buffer_len() - buffer_size_before >= n {
1680                        break;
1681                    }
1682                }
1683            }
1684        }
1685
1686        Ok(state.frame_finished)
1687    }
1688
1689    /// Decode the inner blocks `[start_block, end_block)` of the current
1690    /// frame and return their decompressed bytes as one contiguous buffer.
1691    ///
1692    /// Serves two consumer needs with one call:
1693    ///
1694    /// - **Range-query performance:** decode only the inner zstd blocks that
1695    ///   cover a key range instead of the whole frame. Blocks before
1696    ///   `start_block` are decoded into the window (zstd blocks share one
1697    ///   window, so a leading block's bytes may be the match source for an
1698    ///   in-range block and cannot simply be skipped) but their output is not
1699    ///   returned; blocks at or after `end_block` are not decoded at all,
1700    ///   which is the trailing-block work saving. Map a decompressed byte
1701    ///   offset to a block index with
1702    ///   [`FrameEmitInfo::decompressed_byte_range`].
1703    /// - **Best-effort recovery:** if a block decode fails, decoding stops,
1704    ///   the clean prefix of in-range output is preserved in
1705    ///   [`PartialDecode::data`], and the failure is reported via
1706    ///   [`PartialDecode::stopped_at`]. Passing `(0, u32::MAX)` decodes the
1707    ///   whole frame, stopping at the first corrupt block (pure recovery).
1708    ///
1709    /// `end_block` is exclusive; pass `u32::MAX` to decode to the end of the
1710    /// frame. Call on a freshly [`reset`](Self::reset) decoder (it decodes
1711    /// from the frame's first block).
1712    ///
1713    /// # Resume (cold incremental / top-up)
1714    ///
1715    /// A plain call drains its in-range output from the match window on return,
1716    /// so two consecutive calls cannot resume one another and growing a decoded
1717    /// extent would mean re-decoding the covering prefix from block 0
1718    /// (`O(extent)` per growth, `O(N²)` for a forward walk). The `resume` /
1719    /// `emit_resume` arguments make a symmetric one-call grow-loop possible:
1720    ///
1721    /// - `emit_resume = true` captures the cross-block carry-over state (entropy
1722    ///   tables + repcode history + the next block index / output offset) into
1723    ///   [`PartialDecode::resume_state`]. The entropy-table snapshot clone is
1724    ///   only paid when this is set. The snapshot is `None` when the decode
1725    ///   reaches the frame's last block ([`PartialDecode::frame_finished`]):
1726    ///   there is no following block to resume from, so an incremental walk
1727    ///   stops on `frame_finished` rather than on a `None` snapshot.
1728    /// - `resume = Some(`[`ResumeInput`]`)` continues from a previously emitted
1729    ///   [`ResumeState`] WITHOUT re-decompressing the preceding blocks: the
1730    ///   match window is primed from [`ResumeInput::window_prime`] and the
1731    ///   entropy/repcode tables are restored from the state, so a `Repeat_Mode`
1732    ///   resume block resolves byte-identically to a contiguous decode — even
1733    ///   across a dropped (cold) decoder.
1734    ///
1735    /// When `resume` is `Some`, decoding resumes at
1736    /// [`ResumeState::block_index`] and the `start_block` argument is ignored
1737    /// (pass `resume.state.block_index()`); position `source` at that block's
1738    /// compressed frame offset
1739    /// ([`FrameEmitInfo::blocks`]`[block_index].offset_in_frame`). After a
1740    /// resumed call, [`bytes_read_from_source`](Self::bytes_read_from_source)
1741    /// and any `stopped_at` offsets are relative to the repositioned `source`.
1742    ///
1743    /// **Dictionaries:** [`ResumeState`] does NOT carry the dictionary content.
1744    /// For a dictionary frame, attach the dictionary to the resuming decoder the
1745    /// same way as for a fresh decode — [`reset`](Self::reset) with the
1746    /// dictionary registered (or
1747    /// [`reset_with_dict_handle`](Self::reset_with_dict_handle)) BEFORE this
1748    /// call — so dict-sourced matches near the frame start resolve. The caller
1749    /// already holds the dictionary (it supplied it at encode time), so
1750    /// re-supplying it on resume is free; storing it in the snapshot would only
1751    /// duplicate it. The resume guard records the applied dictionary's identity
1752    /// and rejects ([`FrameDecoderError::ResumeFrameMismatch`]) a resume whose
1753    /// active dictionary differs from the one the snapshot was captured under.
1754    ///
1755    /// # Errors
1756    ///
1757    /// Returns [`FrameDecoderError::NotYetInitialized`] if the decoder has not
1758    /// been reset, [`FrameDecoderError::InvalidBlockRange`] if the effective
1759    /// start exceeds `end_block`, [`FrameDecoderError::ResumeWindowTooShort`]
1760    /// if `resume`'s `window_prime` is shorter than the match window the resume
1761    /// block can reach back into (`min(window_size, output_offset)`), and
1762    /// [`FrameDecoderError::ResumeFrameMismatch`] if the snapshot was captured
1763    /// from a frame with a different decode shape / dictionary, or (with the
1764    /// `hash` feature) a `window_prime` whose content does not match what was
1765    /// captured — all rejected up front rather than silently mis-resolving
1766    /// matches. A corrupt block is NOT an `Err` here: it is reported via
1767    /// [`PartialDecode::stopped_at`] so the clean prefix survives.
1768    ///
1769    /// [`FrameEmitInfo::decompressed_byte_range`]: crate::encoding::frame_emit_info::FrameEmitInfo::decompressed_byte_range
1770    /// [`FrameEmitInfo::blocks`]: crate::encoding::frame_emit_info::FrameEmitInfo::blocks
1771    #[cfg(feature = "lsm")]
1772    #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
1773    pub fn decode_blocks_partial(
1774        &mut self,
1775        mut source: impl Read,
1776        start_block: u32,
1777        end_block: u32,
1778        resume: Option<ResumeInput<'_>>,
1779        emit_resume: bool,
1780    ) -> Result<PartialDecode, FrameDecoderError> {
1781        use FrameDecoderError as err;
1782        #[cfg(feature = "hash")]
1783        let checksum_mode = self.content_checksum;
1784        let magicless = self.magicless;
1785        let state = self.state.as_mut().ok_or(err::NotYetInitialized)?;
1786
1787        // Honor the checksum mode before any drain/read can hash: `None` must
1788        // compute no XXH64. `decode_blocks` sets this; the partial path must too,
1789        // or a reused scratch keeps hashing with the default-enabled state.
1790        #[cfg(feature = "hash")]
1791        {
1792            let compute_hash = checksum_mode != ContentChecksum::None
1793                && state.frame_header.descriptor.content_checksum_flag();
1794            state.decoder_scratch.set_compute_hash(compute_hash);
1795        }
1796
1797        // Mirror `decode_blocks`: pre-reserve the backing buffer to the
1798        // FCS-capped window so multi-block frames don't pay repeated grow
1799        // steps. The RAW frame window stays separately bound — the resume
1800        // logic below bounds match reach by the frame's window semantics,
1801        // not by the (possibly smaller) reservation cap.
1802        let window_size = state.frame_header.window_size().unwrap_or(0) as usize;
1803        let useful_window = state.useful_window_size();
1804        state.decoder_scratch.reserve_buffer(useful_window);
1805
1806        // Cold resume: prime the match window + restore entropy/repcode state +
1807        // advance the block cursor BEFORE the loop, so the first in-range block
1808        // resolves its matches and `Repeat_Mode` tables against the caller's
1809        // persisted state instead of re-decoded prefix blocks. The effective
1810        // start is the resume state's block index (the passed `start_block` is
1811        // ignored in resume mode, per the doc).
1812        let effective_start = if let Some(r) = resume {
1813            // Reject a snapshot captured from a different frame shape BEFORE
1814            // touching any decoder state: restoring entropy/repcode tables that
1815            // belong to another frame would silently produce byte-wrong output.
1816            let current_key = FrameKey::from_state(state, magicless);
1817            if current_key != r.state.frame_key {
1818                return Err(err::ResumeFrameMismatch);
1819            }
1820            let output_offset = r.state.output_offset;
1821            // The window the resume block can reach back into is bounded by the
1822            // smaller of the frame's window_size and the bytes produced so far.
1823            let required = core::cmp::min(window_size as u64, output_offset) as usize;
1824            if r.window_prime.len() < required {
1825                return Err(err::ResumeWindowTooShort {
1826                    got: r.window_prime.len(),
1827                    need: required,
1828                });
1829            }
1830            // Only the most recent `window_size` bytes can ever back a match
1831            // (offset <= window_size by the frame invariant); load just those
1832            // even if the caller handed us a longer prefix, bounding resume
1833            // memory to one window regardless of the skipped prefix's size.
1834            let prime = if r.window_prime.len() > window_size {
1835                &r.window_prime[r.window_prime.len() - window_size..]
1836            } else {
1837                r.window_prime
1838            };
1839            // Content-exact identity: the primed window must hash to what was
1840            // captured at emit. Catches a same-shape-but-different-frame
1841            // snapshot and a wrong/corrupted window_prime (which FrameKey alone
1842            // cannot), before any state is restored. O(window) one-time per
1843            // resume — negligible next to the decode it guards.
1844            #[cfg(feature = "hash")]
1845            if xxh64_of(prime) != r.state.window_hash {
1846                return Err(err::ResumeFrameMismatch);
1847            }
1848            // Validate the effective range (resume mode begins at the resume
1849            // block, ignoring the caller's `start_block`) BEFORE mutating the
1850            // decoder: an inverted `end_block` must fail without priming the
1851            // window / entropy or advancing the cursor, leaving the decoder
1852            // re-resettable rather than in a half-resumed state.
1853            let effective_start = r.state.block_index;
1854            if effective_start > end_block {
1855                return Err(err::InvalidBlockRange {
1856                    start_block: effective_start,
1857                    end_block,
1858                });
1859            }
1860            state.decoder_scratch.restore_entropy(r.state);
1861            state.decoder_scratch.prime_window(prime, output_offset);
1862            state.block_counter = effective_start as usize;
1863            // The caller repositions `source` to the resume block; report
1864            // consumed bytes relative to that point (reset left this at the
1865            // frame-header size).
1866            state.bytes_read_counter = 0;
1867            effective_start
1868        } else {
1869            // Fresh decode: validate the caller's range (no state to mutate).
1870            if start_block > end_block {
1871                return Err(err::InvalidBlockRange {
1872                    start_block,
1873                    end_block,
1874                });
1875            }
1876            start_block
1877        };
1878
1879        let mut block_dec = decoding::block_decoder::new();
1880
1881        // Bytes of prefix-window output that physically precede the first
1882        // in-range block in the buffer. Captured at the prefix → in-range
1883        // transition (after leading blocks were dropped to the window) so we
1884        // can discard exactly those bytes once decoding is done. `None` until
1885        // the first in-range block is reached.
1886        let mut prefix_window_len: Option<usize> = None;
1887        // Exact count of clean in-range decompressed bytes (sum of per-block
1888        // length deltas of the in-range blocks that succeeded). Any partial
1889        // bytes of a failing in-range block are excluded — the fused executor
1890        // rolls the buffer back to the pre-block checkpoint on a sequence
1891        // error, and anything left over is never counted here, so it is not
1892        // drained into `data`.
1893        let mut subset_bytes: u64 = 0;
1894        let mut blocks_decoded: u32 = 0;
1895        let mut stopped_at: Option<(u32, FrameDecoderError)> = None;
1896
1897        loop {
1898            let block_index = state.block_counter as u32;
1899            // Stop before decoding `end_block`: the trailing blocks are never
1900            // touched (the perf win), and the frame's tail is left unread.
1901            if block_index >= end_block || state.frame_finished {
1902                break;
1903            }
1904            let in_range = block_index >= effective_start;
1905            // Snapshot the window length at the prefix → in-range boundary.
1906            if in_range && prefix_window_len.is_none() {
1907                prefix_window_len = Some(state.decoder_scratch.buffer_len());
1908            }
1909
1910            let block_frame_offset = state.bytes_read_counter as u32;
1911            let (block_header, block_header_size) = match block_dec.read_block_header(&mut source) {
1912                Ok(v) => v,
1913                Err(e) => {
1914                    stopped_at = Some((
1915                        block_index,
1916                        block_header_decode_error(e, block_index, block_frame_offset),
1917                    ));
1918                    break;
1919                }
1920            };
1921            state.bytes_read_counter += u64::from(block_header_size);
1922
1923            let len_before = state.decoder_scratch.buffer_len();
1924            // Only expose the held dictionary while THIS frame is dict-backed
1925            // (`using_dict` is set per dict-apply, cleared on reset). A reused
1926            // decoder keeps `active_dict` across a no-dict frame for the
1927            // `ptr::eq` reuse-skip, so it must be gated here or a stray
1928            // out-of-window offset on a dictless frame would resolve against the
1929            // stale dictionary content instead of erroring.
1930            let dict_ref = if state.using_dict.is_some() {
1931                state.active_dict.as_ref().map(|h| h.as_dict())
1932            } else {
1933                None
1934            };
1935            match state.decoder_scratch.decode_block_content(
1936                &mut block_dec,
1937                &block_header,
1938                &mut source,
1939                dict_ref,
1940            ) {
1941                Ok(body_read) => state.bytes_read_counter += body_read,
1942                Err(e) => {
1943                    stopped_at = Some((
1944                        block_index,
1945                        block_body_decode_error(
1946                            e,
1947                            block_index,
1948                            block_frame_offset,
1949                            &block_header,
1950                            block_header_size,
1951                        ),
1952                    ));
1953                    break;
1954                }
1955            }
1956            let produced = state.decoder_scratch.buffer_len() - len_before;
1957            // Per-block XXH64 capture, mirroring `decode_blocks`: hash this
1958            // block's just-decoded bytes BEFORE any window drop so the digest
1959            // count stays 1:1 with the blocks decoded on this path too. Covers
1960            // context (out-of-range) blocks as well, matching `decode_blocks`
1961            // which hashes every block it decodes.
1962            #[cfg(all(feature = "lsm", feature = "hash"))]
1963            if self.per_block_checksums_enabled {
1964                use core::hash::Hasher;
1965                let (s1, s2) = state.decoder_scratch.last_n_as_slices(produced);
1966                let mut h = twox_hash::XxHash64::with_seed(0);
1967                h.write(s1);
1968                h.write(s2);
1969                self.computed_block_checksums.push(h.finish() as u32);
1970            }
1971            state.block_counter += 1;
1972            if in_range {
1973                subset_bytes += produced as u64;
1974                blocks_decoded += 1;
1975            }
1976
1977            if block_header.last_block {
1978                state.frame_finished = true;
1979                if state.frame_header.descriptor.content_checksum_flag() {
1980                    let mut chksum = [0u8; 4];
1981                    match source.read_exact(&mut chksum) {
1982                        Ok(()) => {
1983                            state.bytes_read_counter += 4;
1984                            state.check_sum = Some(u32::from_le_bytes(chksum));
1985                        }
1986                        // A trailing-checksum read failure does not invalidate
1987                        // the decoded bytes; surface it so the caller knows the
1988                        // frame tail was truncated, but keep `data`.
1989                        Err(e) => {
1990                            stopped_at = Some((block_index, err::FailedToReadChecksum(e)));
1991                        }
1992                    }
1993                }
1994                break;
1995            }
1996
1997            // Leading (out-of-range) block: bound memory to the window. We
1998            // must NOT drop once in-range, or the in-range output we are about
1999            // to return would be discarded.
2000            if !in_range {
2001                state.decoder_scratch.buffer_drop_to_window_size();
2002            }
2003        }
2004
2005        // Emit cross-block carry-over state for a later resume, if requested.
2006        // Captured AFTER the loop (entropy tables / repcode history are final)
2007        // but BEFORE the drain — the drain only touches the visible output, not
2008        // the entropy state or `total_output_counter`. `block_counter` /
2009        // `total_output()` give the resume coordinates: the next block to decode
2010        // and the cumulative decompressed offset before it (clean even after an
2011        // early stop, since a failed block rolls both back to its checkpoint).
2012        // Suppress the snapshot on the terminal block: `block_counter` is then
2013        // one past the last block (EOF), for which there is no next-block source
2014        // position to resume from. A resume needs a real following block.
2015        let resume_state = if emit_resume && !state.frame_finished {
2016            let dict_ref = if state.using_dict.is_some() {
2017                state.active_dict.as_ref().map(|h| h.as_dict())
2018            } else {
2019                None
2020            };
2021            let (fse, huf, offset_hist) = state.decoder_scratch.export_entropy(dict_ref);
2022            Some(ResumeState {
2023                frame_key: FrameKey::from_state(state, magicless),
2024                block_index: state.block_counter as u32,
2025                output_offset: state.decoder_scratch.total_output(),
2026                fse,
2027                huf,
2028                offset_hist,
2029                #[cfg(feature = "hash")]
2030                window_hash: state.decoder_scratch.window_tail_hash(window_size),
2031            })
2032        } else {
2033            None
2034        };
2035
2036        // The visible buffer is now `[prefix window][in-range clean][maybe
2037        // trailing garbage from a failed in-range block]`. Drop the prefix
2038        // window from the front (match resolution is complete, so it is no
2039        // longer needed), then drain exactly the clean in-range byte count.
2040        let w = prefix_window_len.unwrap_or(0);
2041        state.decoder_scratch.buffer_discard_front(w);
2042        let mut data = alloc::vec![0u8; subset_bytes as usize];
2043        state
2044            .decoder_scratch
2045            .buffer_read_all(&mut data)
2046            .map_err(err::FailedToDrainDecodebuffer)?;
2047
2048        // Clear anything still buffered so a later `read()`/`collect()` on this
2049        // decoder cannot surface out-of-range bytes: the leading-block window
2050        // when no in-range block was reached (`prefix_window_len` stayed
2051        // `None`, so `w` was 0), or trailing garbage from a failed in-range
2052        // block. Only the returned `data` is the partial decode's output.
2053        let residual = state.decoder_scratch.buffer_len();
2054        state.decoder_scratch.buffer_discard_front(residual);
2055
2056        Ok(PartialDecode {
2057            data,
2058            start_block: effective_start,
2059            blocks_decoded,
2060            stopped_at,
2061            frame_finished: state.frame_finished,
2062            resume_state,
2063        })
2064    }
2065
2066    /// Collect bytes and retain window_size bytes while decoding is still going on.
2067    /// After decoding of the frame (is_finished() == true) has finished it will collect all remaining bytes
2068    pub fn collect(&mut self) -> Option<Vec<u8>> {
2069        let finished = self.is_finished();
2070        let state = self.state.as_mut()?;
2071        if finished {
2072            Some(state.decoder_scratch.buffer_drain())
2073        } else {
2074            state.decoder_scratch.buffer_drain_to_window_size()
2075        }
2076    }
2077
2078    /// Collect bytes and retain window_size bytes while decoding is still going on.
2079    /// After decoding of the frame (is_finished() == true) has finished it will collect all remaining bytes
2080    pub fn collect_to_writer(&mut self, w: impl Write) -> Result<usize, Error> {
2081        let finished = self.is_finished();
2082        let state = match &mut self.state {
2083            None => return Ok(0),
2084            Some(s) => s,
2085        };
2086        if finished {
2087            state.decoder_scratch.buffer_drain_to_writer(w)
2088        } else {
2089            state.decoder_scratch.buffer_drain_to_window_size_writer(w)
2090        }
2091    }
2092
2093    /// How many bytes can currently be collected from the decodebuffer, while decoding is going on this will be lower than the actual decodbuffer size
2094    /// because window_size bytes need to be retained for decoding.
2095    /// After decoding of the frame (is_finished() == true) has finished it will report all remaining bytes
2096    pub fn can_collect(&self) -> usize {
2097        let finished = self.is_finished();
2098        let state = match &self.state {
2099            None => return 0,
2100            Some(s) => s,
2101        };
2102        if finished {
2103            state.decoder_scratch.buffer_can_drain()
2104        } else {
2105            state
2106                .decoder_scratch
2107                .buffer_can_drain_to_window_size()
2108                .unwrap_or(0)
2109        }
2110    }
2111
2112    /// Decodes as many blocks as possible from the source slice and reads from the decodebuffer into the target slice
2113    /// The source slice may contain only parts of a frame but must contain at least one full block to make progress
2114    ///
2115    /// By all means use decode_blocks if you have a io.Reader available. This is just for compatibility with other decompressors
2116    /// which try to serve an old-style c api
2117    ///
2118    /// Returns (read, written), if read == 0 then the source did not contain a full block and further calls with the same
2119    /// input will not make any progress!
2120    ///
2121    /// Note that no kind of block can be bigger than 128kb.
2122    /// So to be safe use at least 128*1024 (max block content size) + 3 (block_header size) + 18 (max frame_header size) bytes as your source buffer
2123    ///
2124    /// You may call this function with an empty source after all bytes have been decoded. This is equivalent to just call decoder.read(&mut target)
2125    pub fn decode_from_to(
2126        &mut self,
2127        source: &[u8],
2128        target: &mut [u8],
2129    ) -> Result<(usize, usize), FrameDecoderError> {
2130        use FrameDecoderError as err;
2131        let bytes_read_at_start = match &self.state {
2132            Some(s) => s.bytes_read_counter,
2133            None => 0,
2134        };
2135
2136        if !self.is_finished() || self.state.is_none() {
2137            let mut mt_source = source;
2138
2139            if self.state.is_none() {
2140                self.init(&mut mt_source)?;
2141            }
2142
2143            //pseudo block to scope "state" so we can borrow self again after the block
2144            {
2145                let state = match &mut self.state {
2146                    Some(s) => s,
2147                    None => panic!("Bug in library"),
2148                };
2149                let mut block_dec = decoding::block_decoder::new();
2150
2151                // Honour the content-checksum mode on this hand-rolled decode
2152                // loop (it does not go through `decode_blocks`): hash only when
2153                // a digest is wanted and the frame carries one. `None` skips the
2154                // XXH64 pass; verification happens after the final drain below.
2155                #[cfg(feature = "hash")]
2156                {
2157                    let compute_hash = self.content_checksum != ContentChecksum::None
2158                        && state.frame_header.descriptor.content_checksum_flag();
2159                    state.decoder_scratch.set_compute_hash(compute_hash);
2160                }
2161
2162                if state.frame_header.descriptor.content_checksum_flag()
2163                    && state.frame_finished
2164                    && state.check_sum.is_none()
2165                {
2166                    // The trailing checksum arrived on a separate call (the last
2167                    // block finished earlier). Consume it and fall through to the
2168                    // shared `self.read` + post-drain verify below — NOT an early
2169                    // return — so any output still buffered from a prior
2170                    // small-`target` call is flushed on this call too, and the
2171                    // checksum is verified through the one shared path.
2172                    if mt_source.len() >= 4 {
2173                        let chksum = mt_source[..4].try_into().expect("optimized away");
2174                        state.bytes_read_counter += 4;
2175                        let chksum = u32::from_le_bytes(chksum);
2176                        state.check_sum = Some(chksum);
2177                        mt_source = &mt_source[4..];
2178                    }
2179                }
2180
2181                loop {
2182                    // The frame is fully decoded (last block seen, trailer
2183                    // consumed above); no more blocks to read. Any leftover
2184                    // bytes are not a block header — stop before misreading them.
2185                    if state.frame_finished {
2186                        break;
2187                    }
2188                    //check if there are enough bytes for the next header
2189                    if mt_source.len() < 3 {
2190                        break;
2191                    }
2192                    let block_index = state.block_counter as u32;
2193                    let block_frame_offset = state.bytes_read_counter as u32;
2194                    let (block_header, block_header_size) = block_dec
2195                        .read_block_header(&mut mt_source)
2196                        .map_err(|source| {
2197                            block_header_decode_error(source, block_index, block_frame_offset)
2198                        })?;
2199
2200                    // check the needed size for the block before updating counters.
2201                    // If not enough bytes are in the source, the header will have to be read again, so act like we never read it in the first place
2202                    if mt_source.len() < block_header.content_size as usize {
2203                        break;
2204                    }
2205                    state.bytes_read_counter += u64::from(block_header_size);
2206
2207                    // Only expose the held dictionary while THIS frame is dict-backed
2208                    // (`using_dict` is set per dict-apply, cleared on reset). A reused
2209                    // decoder keeps `active_dict` across a no-dict frame for the
2210                    // `ptr::eq` reuse-skip, so it must be gated here or a stray
2211                    // out-of-window offset on a dictless frame would resolve against the
2212                    // stale dictionary content instead of erroring.
2213                    let dict_ref = if state.using_dict.is_some() {
2214                        state.active_dict.as_ref().map(|h| h.as_dict())
2215                    } else {
2216                        None
2217                    };
2218                    let bytes_read_in_block_body = state
2219                        .decoder_scratch
2220                        .decode_block_content(
2221                            &mut block_dec,
2222                            &block_header,
2223                            &mut mt_source,
2224                            dict_ref,
2225                        )
2226                        .map_err(|source| {
2227                            block_body_decode_error(
2228                                source,
2229                                block_index,
2230                                block_frame_offset,
2231                                &block_header,
2232                                block_header_size,
2233                            )
2234                        })?;
2235                    state.bytes_read_counter += bytes_read_in_block_body;
2236                    state.block_counter += 1;
2237
2238                    if block_header.last_block {
2239                        state.frame_finished = true;
2240                        if state.frame_header.descriptor.content_checksum_flag() {
2241                            //if there are enough bytes handle this here. Else the block at the start of this function will handle it at the next call
2242                            if mt_source.len() >= 4 {
2243                                let chksum = mt_source[..4].try_into().expect("optimized away");
2244                                state.bytes_read_counter += 4;
2245                                let chksum = u32::from_le_bytes(chksum);
2246                                state.check_sum = Some(chksum);
2247                            }
2248                        }
2249                        break;
2250                    }
2251                }
2252            }
2253        }
2254
2255        let result_len = self.read(target).map_err(err::FailedToDrainDecodebuffer)?;
2256        // Once the frame is fully decoded and drained, the running digest is
2257        // final: validate it in `Verify` mode (no-op otherwise). Same finish
2258        // point as the streaming reader.
2259        #[cfg(feature = "hash")]
2260        if self.is_finished() && self.can_collect() == 0 {
2261            self.verify_content_checksum()?;
2262        }
2263        let bytes_read_at_end = match &mut self.state {
2264            Some(s) => s.bytes_read_counter,
2265            None => panic!("Bug in library"),
2266        };
2267        let read_len = bytes_read_at_end - bytes_read_at_start;
2268        Ok((read_len as usize, result_len))
2269    }
2270
2271    /// Decode multiple frames into the output slice.
2272    ///
2273    /// `input` must contain an exact number of frames. Skippable frames are allowed and will be
2274    /// skipped during decode.
2275    ///
2276    /// `output` must be large enough to hold the decompressed data. If you don't know
2277    /// how large the output will be, use [`FrameDecoder::decode_blocks`] instead.
2278    ///
2279    /// This calls [`FrameDecoder::init`], and all bytes currently in the decoder will be lost.
2280    ///
2281    /// Returns the number of bytes written to `output`.
2282    pub fn decode_all(
2283        &mut self,
2284        input: &[u8],
2285        output: &mut [u8],
2286    ) -> Result<usize, FrameDecoderError> {
2287        #[cfg(not(feature = "lsm"))]
2288        {
2289            self.decode_all_impl(input, output, |this, src| this.init(src))
2290        }
2291        #[cfg(feature = "lsm")]
2292        {
2293            self.decode_all_impl(input, output, |this, src| this.init(src), None)
2294        }
2295    }
2296
2297    /// Decode multiple frames into the output slice, invoking `visitor`
2298    /// for every skippable frame encountered before advancing past it.
2299    ///
2300    /// `input` must contain an exact number of frames. Skippable frames
2301    /// (RFC 8878 §3.1.2 magic numbers `0x184D2A50..=0x184D2A5F`) are
2302    /// allowed and will be both visited AND skipped: the visitor gets
2303    /// `(magic_variant, payload)` where `magic_variant` is the low
2304    /// nibble of the magic (`magic - 0x184D2A50`, range `0..=15`) and
2305    /// `payload` is a borrowed slice of the on-wire payload bytes (the
2306    /// skippable frame's `Frame_Size` field worth of data) into
2307    /// `input` — no allocation.
2308    ///
2309    /// The visitor sees skippable frames in stream order; interleaved
2310    /// regular zstd frames continue to decompress into `output` exactly
2311    /// as `decode_all` does.
2312    ///
2313    /// `output` must be large enough to hold the decompressed data.
2314    /// Returns the number of bytes written to `output`.
2315    ///
2316    /// # Example
2317    ///
2318    /// ```ignore
2319    /// use structured_zstd::decoding::FrameDecoder;
2320    ///
2321    /// let mut decoder = FrameDecoder::new();
2322    /// let mut output = vec![0u8; 1024];
2323    /// let mut collected: Vec<(u8, Vec<u8>)> = Vec::new();
2324    /// let n = decoder.decode_all_with_skippable_visitor(
2325    ///     input,
2326    ///     &mut output,
2327    ///     |variant, payload| collected.push((variant, payload.to_vec())),
2328    /// )?;
2329    /// ```
2330    #[cfg(feature = "lsm")]
2331    #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
2332    pub fn decode_all_with_skippable_visitor<F>(
2333        &mut self,
2334        input: &[u8],
2335        output: &mut [u8],
2336        mut visitor: F,
2337    ) -> Result<usize, FrameDecoderError>
2338    where
2339        F: FnMut(u8, &[u8]),
2340    {
2341        self.decode_all_impl(
2342            input,
2343            output,
2344            |this, src| this.init(src),
2345            Some(&mut visitor),
2346        )
2347    }
2348
2349    /// Decode multiple frames into the output slice using a pre-parsed dictionary handle.
2350    ///
2351    /// `input` must contain an exact number of frames. Skippable frames are allowed and will be
2352    /// skipped during decode.
2353    ///
2354    /// `output` must be large enough to hold the decompressed data. If you don't know
2355    /// how large the output will be, use [`FrameDecoder::decode_blocks`] instead.
2356    ///
2357    /// This calls [`FrameDecoder::init_with_dict_handle`], and all bytes currently in the
2358    /// decoder will be lost.
2359    ///
2360    /// # Warning
2361    ///
2362    /// Each decoded frame is initialized with `dict`, even when a frame header
2363    /// omits the optional dictionary ID. Callers must only use this API when
2364    /// they already know the input frames were encoded with the provided
2365    /// dictionary; otherwise decoded output can be silently corrupted.
2366    pub fn decode_all_with_dict_handle(
2367        &mut self,
2368        input: &[u8],
2369        output: &mut [u8],
2370        dict: &DictionaryHandle,
2371    ) -> Result<usize, FrameDecoderError> {
2372        #[cfg(not(feature = "lsm"))]
2373        {
2374            self.decode_all_impl(input, output, |this, src| {
2375                this.init_with_dict_handle(src, dict)
2376            })
2377        }
2378        #[cfg(feature = "lsm")]
2379        {
2380            self.decode_all_impl(
2381                input,
2382                output,
2383                |this, src| this.init_with_dict_handle(src, dict),
2384                None,
2385            )
2386        }
2387    }
2388
2389    /// Whether the decoder sits at the very start of an initialised frame:
2390    /// the header has been read (state populated) but no block has been
2391    /// decoded and the frame is not finished. In this state the wrapped
2392    /// source is positioned exactly after the frame header, so
2393    /// [`Self::decode_current_frame_to_vec`] can decode the rest of the frame
2394    /// straight from the remaining source bytes.
2395    pub(crate) fn is_at_frame_start(&self) -> bool {
2396        self.state
2397            .as_ref()
2398            .is_some_and(|s| s.block_counter == 0 && !s.frame_finished)
2399    }
2400
2401    /// Decode the CURRENT (already-initialised) frame, APPENDING the
2402    /// decompressed bytes to `output`, and return the number appended.
2403    ///
2404    /// `input` must be the frame's post-header bytes (the wrapped source after
2405    /// `init` consumed the header). Unlike [`Self::decode_all_to_vec`] this
2406    /// neither re-reads a header nor requires the caller to pre-reserve
2407    /// capacity: a frame that declares its content size decodes DIRECTLY into
2408    /// freshly-grown `output` capacity via the single-copy direct path
2409    /// ([`Self::run_direct_decode`]) — bypassing the `Ring`/`FlatBuf` →
2410    /// `read()` drain copy the streaming loop pays — while an unsized frame
2411    /// falls back to the window-bounded ring drain (still one copy, into
2412    /// `output`). Backs [`StreamingDecoder`](crate::decoding::StreamingDecoder)'s
2413    /// `read_to_end` fast path; the caller must ensure
2414    /// [`Self::is_at_frame_start`].
2415    ///
2416    /// # Errors
2417    ///
2418    /// Propagates any [`FrameDecoderError`] from block decode, content-size
2419    /// mismatch, or (in `Verify` mode) checksum validation.
2420    pub(crate) fn decode_current_frame_to_vec(
2421        &mut self,
2422        mut input: &[u8],
2423        output: &mut Vec<u8>,
2424        dict: Option<&DictionaryHandle>,
2425    ) -> Result<usize, FrameDecoderError> {
2426        let start_len = output.len();
2427        // The current frame is already initialised (its header consumed by the
2428        // caller, WITH `dict` applied if the decoder was constructed with one).
2429        // Decode it, then decode any FOLLOWING concatenated / skippable frames
2430        // in `input` so the whole source is consumed to EOF and nothing is
2431        // dropped (matching `read_to_end` semantics).
2432        self.decode_one_frame_to_vec(&mut input, output)?;
2433        self.decode_concatenated_frames_to_vec(&mut input, output, dict)?;
2434        Ok(output.len() - start_len)
2435    }
2436
2437    /// Initialise and decode every frame remaining in `input` (concatenated /
2438    /// skippable), APPENDING to `output`. `input` is advanced as frames are
2439    /// consumed; on return it is empty. Re-initialisation honours `dict`: when
2440    /// `Some`, each following frame is initialised via
2441    /// [`Self::init_with_dict_handle`] so a forced dictionary is preserved even
2442    /// for frames that omit the dictionary id (plain [`Self::init`] would
2443    /// resolve dictionaries by id only). Backs the `read_to_end` fast path (the
2444    /// frames after the current one) and its mid-frame fallback (the frames
2445    /// after the partially-read one).
2446    pub(crate) fn decode_concatenated_frames_to_vec(
2447        &mut self,
2448        input: &mut &[u8],
2449        output: &mut Vec<u8>,
2450        dict: Option<&DictionaryHandle>,
2451    ) -> Result<usize, FrameDecoderError> {
2452        let start_len = output.len();
2453        while !input.is_empty() {
2454            let init_result = match dict {
2455                Some(d) => self.init_with_dict_handle(&mut *input, d),
2456                None => self.init(&mut *input),
2457            };
2458            match init_result {
2459                Ok(_) => {}
2460                Err(FrameDecoderError::ReadFrameHeaderError(
2461                    crate::decoding::errors::ReadFrameHeaderError::SkipFrame { length, .. },
2462                )) => {
2463                    *input = input
2464                        .get(length as usize..)
2465                        .ok_or(FrameDecoderError::FailedToSkipFrame)?;
2466                    continue;
2467                }
2468                Err(e) => return Err(e),
2469            }
2470            self.decode_one_frame_to_vec(&mut *input, output)?;
2471        }
2472        Ok(output.len() - start_len)
2473    }
2474
2475    /// Decode the single CURRENT (already-initialised) frame, APPENDING to
2476    /// `output`. Helper for [`Self::decode_current_frame_to_vec`].
2477    fn decode_one_frame_to_vec(
2478        &mut self,
2479        input: &mut &[u8],
2480        output: &mut Vec<u8>,
2481    ) -> Result<usize, FrameDecoderError> {
2482        let frame_start = output.len();
2483        let (content_size, fcs_declared) = {
2484            let s = self.state.as_ref().expect("frame is initialised");
2485            (
2486                s.frame_header.frame_content_size(),
2487                s.frame_header.fcs_declared(),
2488            )
2489        };
2490        // Direct path: a declared, non-empty content size that FITS in `usize`
2491        // (and whose end offset does not overflow). `usize::try_from` guards the
2492        // 32-bit / oversized-FCS truncation; an unrepresentable size falls
2493        // through to the window-bounded ring drain rather than allocating a
2494        // truncated buffer that would violate `run_direct_decode`'s precondition.
2495        //
2496        // Plausibility gate: the direct path `resize`s `output` to the declared
2497        // size up front, so a tiny/truncated frame declaring a huge (but
2498        // representable) FCS would allocate + zero that whole size before the
2499        // body is validated. zstd's per-block ceiling is MAX_BLOCK_SIZE from as
2500        // little as ~4 input bytes, so the declared size cannot legitimately
2501        // exceed `input.len() * (MAX_BLOCK_SIZE / 4)`. Anything larger falls
2502        // through to the ring drain, which grows only as real bytes are produced
2503        // and errors out cheaply on truncated input. `input` spans the remaining
2504        // source (this frame plus any following ones), so the bound only ever
2505        // over-permits — a legitimate frame is never forced off the direct path.
2506        // saturating_mul is intentional: an overflow means the available input
2507        // is so large that any representable FCS is plausible (cap = "no limit").
2508        const MAX_DECOMPRESSION_RATIO: usize = (crate::common::MAX_BLOCK_SIZE / 4) as usize;
2509        if content_size > 0
2510            && let Ok(cs) = usize::try_from(content_size)
2511            && cs <= input.len().saturating_mul(MAX_DECOMPRESSION_RATIO)
2512            && let Some(frame_end) = frame_start.checked_add(cs)
2513        {
2514            // Reserve exactly the frame's content and decode straight into it
2515            // (single copy, no ring). The direct path writes precisely
2516            // `content_size` bytes (erroring otherwise), so the grown region is
2517            // fully written.
2518            output.resize(frame_end, 0);
2519            // On error, drop the just-grown (zeroed) tail before propagating so
2520            // callers never observe bytes that were never decoded.
2521            let written =
2522                match self.run_direct_decode(&mut *input, &mut output[frame_start..], content_size)
2523                {
2524                    Ok(n) => n,
2525                    Err(e) => {
2526                        output.truncate(frame_start);
2527                        return Err(e);
2528                    }
2529                };
2530            output.truncate(frame_start + written);
2531            #[cfg(feature = "hash")]
2532            self.verify_content_checksum()?;
2533            return Ok(written);
2534        }
2535        // The ring-drain fallback below pre-reserves `useful_window_size()`
2536        // (= `window.min(FCS)`), which for a single-segment frame is the
2537        // declared FCS itself — so a truncated single-segment frame lying about
2538        // its size would still allocate the pledged window before the body
2539        // errors, sidestepping the direct-path gate above. Reject such a frame
2540        // up front when its declared (FCS-bearing) window exceeds what the
2541        // available input could plausibly produce. Frames without a declared
2542        // size keep their window-descriptor reservation (already capped at
2543        // `MAXIMUM_ALLOWED_WINDOW_SIZE` at init); a small-window multi-segment
2544        // frame still falls through to the ring drain, which errors cheaply on
2545        // the truncated body.
2546        if fcs_declared
2547            && let Some(state) = self.state.as_ref()
2548            && state.useful_window_size() > input.len().saturating_mul(MAX_DECOMPRESSION_RATIO)
2549        {
2550            return Err(FrameDecoderError::FrameContentSizeMismatch {
2551                declared: content_size,
2552                produced: 0,
2553            });
2554        }
2555        // No declared size, explicit FCS=0, or an unrepresentable FCS: window-
2556        // bounded ring drain, appended directly to `output` via
2557        // `collect_to_writer` (no staging buffer).
2558        loop {
2559            self.decode_blocks(&mut *input, BlockDecodingStrategy::UptoBytes(1024 * 1024))?;
2560            self.collect_to_writer(&mut *output)
2561                .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
2562            if self.is_finished() {
2563                // Final flush of the retained window tail.
2564                self.collect_to_writer(&mut *output)
2565                    .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
2566                break;
2567            }
2568        }
2569        let produced = (output.len() - frame_start) as u64;
2570        // A declared content size MUST match what the body produced — otherwise
2571        // accept the same corrupt frames `decode_all_impl` rejects (e.g. an
2572        // explicit FCS=0 whose body emits bytes). Use `fcs_declared()` so an
2573        // on-wire FCS=0 is validated, while an unknown size is not.
2574        if fcs_declared && produced != content_size {
2575            return Err(FrameDecoderError::FrameContentSizeMismatch {
2576                declared: content_size,
2577                produced,
2578            });
2579        }
2580        #[cfg(feature = "hash")]
2581        self.verify_content_checksum()?;
2582        Ok(produced as usize)
2583    }
2584
2585    /// Default-feature decode_all_impl: no visitor parameter so the
2586    /// no-lsm build's call surface and codegen are byte-identical to
2587    /// the pre-#172 implementation. Compiles only when `lsm` is OFF.
2588    #[cfg(not(feature = "lsm"))]
2589    fn decode_all_impl(
2590        &mut self,
2591        mut input: &[u8],
2592        mut output: &mut [u8],
2593        mut init_frame: impl FnMut(&mut Self, &mut &[u8]) -> Result<(), FrameDecoderError>,
2594    ) -> Result<usize, FrameDecoderError> {
2595        let mut total_bytes_written = 0;
2596        while !input.is_empty() {
2597            match init_frame(self, &mut input) {
2598                Ok(_) => {}
2599                Err(FrameDecoderError::ReadFrameHeaderError(
2600                    crate::decoding::errors::ReadFrameHeaderError::SkipFrame { length, .. },
2601                )) => {
2602                    input = input
2603                        .get(length as usize..)
2604                        .ok_or(FrameDecoderError::FailedToSkipFrame)?;
2605                    continue;
2606                }
2607                Err(e) => return Err(e),
2608            };
2609            // Per-frame direct-path dispatch. Now safe to route the
2610            // public `decode_all` here because
2611            // `UserSliceBackend::exec_sequence_inline` returns
2612            // `Result<(), ExecuteSequencesError>` instead of
2613            // panicking on capacity overflow; the error propagates
2614            // up as `FrameDecoderError`. Eligibility (FCS > 0,
2615            // remaining `output` slice holds the declared content)
2616            // puts the frame on the fast path that bypasses the
2617            // FlatBuf/Ring -> `read()` drain copy. Ineligible frames
2618            // (no FCS, output too small) fall through to the legacy
2619            // `decode_blocks` + `read` drain loop below. Dictionary
2620            // frames are eligible: `run_direct_decode` hands the
2621            // shared dict handle to its buffer, and beyond-prefix
2622            // offsets resolve through `repeat_from_dict`.
2623            let (content_size, fcs_declared) = {
2624                let state_ref = self.state.as_ref().expect("init populated state");
2625                (
2626                    state_ref.frame_header.frame_content_size(),
2627                    state_ref.frame_header.fcs_declared(),
2628                )
2629            };
2630            // Direct decode requires only that the caller slice holds the
2631            // declared content; the inline sequence-exec path no longer
2632            // needs `WILDCOPY_OVERLENGTH` trailing slack because the
2633            // trailing sequence(s) take the bounded (non-overshooting)
2634            // copy in `UserSliceBackend::exec_sequence_bounded`. This is
2635            // the universal "decode into an FCS-sized buffer" case (a
2636            // caller sizing `output` to exactly `frame_content_size`),
2637            // so dropping the slack requirement halves its peak alloc.
2638            //
2639            // Per-block checksums collected inside `run_direct_decode`
2640            // post-loop (over recorded (start, end) ranges of `output`)
2641            // so the direct path stays eligible AND keeps the
2642            // window-size cap (`drop_to_window_size`) between blocks
2643            // that the spec relies on for `offset <= window_size`
2644            // validation. Path choice no longer alters checksum
2645            // semantics.
2646            let direct_eligible = content_size > 0 && (output.len() as u64) >= content_size;
2647            if direct_eligible {
2648                let written = self.run_direct_decode(&mut input, output, content_size)?;
2649                output = &mut output[written..];
2650                total_bytes_written += written;
2651                // Per-frame content-checksum verification (no-op unless the
2652                // mode is `Verify` and the frame carries a checksum).
2653                #[cfg(feature = "hash")]
2654                self.verify_content_checksum()?;
2655                continue;
2656            }
2657            // Non-direct fallback: pre-reserve the backing buffer to
2658            // `window_size` in a single allocation before block decode
2659            // starts, so multi-segment frames don't pay repeated
2660            // `reserve_amortized` grow steps as blocks accumulate (each
2661            // block only reserves MAX_BLOCK_SIZE = 128 KiB, so a window
2662            // > 128 KiB otherwise grows through several intermediate
2663            // sizes with `alloc_zeroed + memcpy` each time).
2664            if let Some(state) = self.state.as_mut() {
2665                // FCS-capped via `useful_window_size` — the same cap
2666                // `decode_blocks` applies, so its per-iteration reserve in
2667                // the loop below cannot grow the buffer back to the raw
2668                // frame window.
2669                let useful_window = state.useful_window_size();
2670                state.decoder_scratch.reserve_buffer(useful_window);
2671            }
2672            let frame_start_total = total_bytes_written;
2673            loop {
2674                self.decode_blocks(&mut input, BlockDecodingStrategy::UptoBytes(1024 * 1024))?;
2675                let bytes_written = self
2676                    .read(output)
2677                    .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
2678                output = &mut output[bytes_written..];
2679                total_bytes_written += bytes_written;
2680                if self.can_collect() != 0 {
2681                    return Err(FrameDecoderError::TargetTooSmall);
2682                }
2683                if self.is_finished() {
2684                    break;
2685                }
2686            }
2687            // Per-frame FCS validation on the legacy fallback path.
2688            // Use `fcs_declared()` (NOT `content_size > 0`) so an
2689            // empty frame with explicit FCS=0 on the wire still gets
2690            // validated.
2691            if fcs_declared {
2692                let produced = (total_bytes_written - frame_start_total) as u64;
2693                if produced != content_size {
2694                    return Err(FrameDecoderError::FrameContentSizeMismatch {
2695                        declared: content_size,
2696                        produced,
2697                    });
2698                }
2699            }
2700            // Per-frame content-checksum verification on the drain path: the
2701            // frame is fully decoded and drained here (is_finished + nothing
2702            // left to collect), so the running digest and stored value are
2703            // final. No-op unless the mode is `Verify`.
2704            #[cfg(feature = "hash")]
2705            self.verify_content_checksum()?;
2706        }
2707
2708        Ok(total_bytes_written)
2709    }
2710
2711    /// `lsm`-feature decode_all_impl: adds the optional skippable
2712    /// visitor parameter consumed by
2713    /// [`Self::decode_all_with_skippable_visitor`]. Mirrors the no-lsm
2714    /// variant including the direct-path dispatch + FCS-validation
2715    /// rationale comments, so the two functions stay in sync; the only
2716    /// behavioral difference is the SkipFrame arm, which uses
2717    /// `split_at(length)` (single bounds check) instead of two
2718    /// separate `get(..length)` / `get(length..)` slices and invokes
2719    /// the visitor (when `Some`) on the borrowed payload before
2720    /// advancing past it.
2721    #[cfg(feature = "lsm")]
2722    #[allow(clippy::type_complexity)]
2723    fn decode_all_impl(
2724        &mut self,
2725        mut input: &[u8],
2726        mut output: &mut [u8],
2727        mut init_frame: impl FnMut(&mut Self, &mut &[u8]) -> Result<(), FrameDecoderError>,
2728        mut skippable_visitor: Option<&mut dyn FnMut(u8, &[u8])>,
2729    ) -> Result<usize, FrameDecoderError> {
2730        let mut total_bytes_written = 0;
2731        while !input.is_empty() {
2732            match init_frame(self, &mut input) {
2733                Ok(_) => {}
2734                Err(FrameDecoderError::ReadFrameHeaderError(
2735                    crate::decoding::errors::ReadFrameHeaderError::SkipFrame {
2736                        magic_number,
2737                        length,
2738                    },
2739                )) => {
2740                    let length = length as usize;
2741                    // Visitor sees the payload slice BEFORE we advance
2742                    // past it. Borrowed slice — no allocation. The
2743                    // variant is the low nibble of the magic number
2744                    // (RFC 8878 §3.1.2). `read_frame_header` only emits
2745                    // SkipFrame for magic in 0x184D2A50..=0x184D2A5F, so
2746                    // the subtraction fits in 0..=15.
2747                    if input.len() < length {
2748                        return Err(FrameDecoderError::FailedToSkipFrame);
2749                    }
2750                    let (payload, rest) = input.split_at(length);
2751                    if let Some(visitor) = skippable_visitor.as_mut() {
2752                        let variant = (magic_number - 0x184D2A50) as u8;
2753                        visitor(variant, payload);
2754                    }
2755                    input = rest;
2756                    continue;
2757                }
2758                Err(e) => return Err(e),
2759            };
2760            // Per-frame direct-path dispatch. Now safe to route the
2761            // public `decode_all` here because
2762            // `UserSliceBackend::exec_sequence_inline` returns
2763            // `Result<(), ExecuteSequencesError>` instead of
2764            // panicking on capacity overflow; the error propagates
2765            // up as `FrameDecoderError`. Eligibility (FCS > 0,
2766            // remaining `output` slice holds the declared content)
2767            // puts the frame on the fast path that bypasses the
2768            // FlatBuf/Ring -> `read()` drain copy. Ineligible frames
2769            // (no FCS, output too small) fall through to the legacy
2770            // `decode_blocks` + `read` drain loop below. Dictionary
2771            // frames are eligible (see the no-lsm path above).
2772            let (content_size, fcs_declared) = {
2773                let state_ref = self.state.as_ref().expect("init populated state");
2774                (
2775                    state_ref.frame_header.frame_content_size(),
2776                    state_ref.frame_header.fcs_declared(),
2777                )
2778            };
2779            // Only `cap >= frame_content_size` needed; the trailing
2780            // sequence(s) take the bounded copy in
2781            // `UserSliceBackend::exec_sequence_bounded`, so no
2782            // `WILDCOPY_OVERLENGTH` trailing slack is required (see the
2783            // no-lsm path above).
2784            let direct_eligible = content_size > 0 && (output.len() as u64) >= content_size;
2785            if direct_eligible {
2786                let written = self.run_direct_decode(&mut input, output, content_size)?;
2787                output = &mut output[written..];
2788                total_bytes_written += written;
2789                // Per-frame content-checksum verification (no-op unless the
2790                // mode is `Verify` and the frame carries a checksum).
2791                #[cfg(feature = "hash")]
2792                self.verify_content_checksum()?;
2793                continue;
2794            }
2795            // Non-direct fallback: pre-reserve the backing buffer to
2796            // `window_size` once so the per-block growth cycle is
2797            // skipped (see same comment on the no-lsm path above).
2798            if let Some(state) = self.state.as_mut() {
2799                // FCS-capped via `useful_window_size` — the same cap
2800                // `decode_blocks` applies, so its per-iteration reserve in
2801                // the loop below cannot grow the buffer back to the raw
2802                // frame window.
2803                let useful_window = state.useful_window_size();
2804                state.decoder_scratch.reserve_buffer(useful_window);
2805            }
2806            let frame_start_total = total_bytes_written;
2807            loop {
2808                self.decode_blocks(&mut input, BlockDecodingStrategy::UptoBytes(1024 * 1024))?;
2809                let bytes_written = self
2810                    .read(output)
2811                    .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
2812                output = &mut output[bytes_written..];
2813                total_bytes_written += bytes_written;
2814                if self.can_collect() != 0 {
2815                    return Err(FrameDecoderError::TargetTooSmall);
2816                }
2817                if self.is_finished() {
2818                    break;
2819                }
2820            }
2821            // Per-frame FCS validation on the legacy fallback path.
2822            // Use `fcs_declared()` (NOT `content_size > 0`) so an
2823            // empty frame with explicit FCS=0 on the wire still gets
2824            // validated.
2825            if fcs_declared {
2826                let produced = (total_bytes_written - frame_start_total) as u64;
2827                if produced != content_size {
2828                    return Err(FrameDecoderError::FrameContentSizeMismatch {
2829                        declared: content_size,
2830                        produced,
2831                    });
2832                }
2833            }
2834            // Per-frame content-checksum verification on the drain path: the
2835            // frame is fully decoded and drained here (is_finished + nothing
2836            // left to collect), so the running digest and stored value are
2837            // final. No-op unless the mode is `Verify`.
2838            #[cfg(feature = "hash")]
2839            self.verify_content_checksum()?;
2840        }
2841
2842        Ok(total_bytes_written)
2843    }
2844
2845    /// Decode multiple frames into the output slice using a serialized dictionary.
2846    ///
2847    /// # Warning
2848    ///
2849    /// Each decoded frame is initialized with the parsed dictionary, even when a
2850    /// frame header omits the optional dictionary ID. Callers must only use this
2851    /// API when they already know the input frames were encoded with that
2852    /// dictionary; otherwise decoded output can be silently corrupted.
2853    pub fn decode_all_with_dict_bytes(
2854        &mut self,
2855        input: &[u8],
2856        output: &mut [u8],
2857        raw_dictionary: &[u8],
2858    ) -> Result<usize, FrameDecoderError> {
2859        let dict = DictionaryHandle::decode_dict(raw_dictionary)?;
2860        self.decode_all_with_dict_handle(input, output, &dict)
2861    }
2862
2863    /// Decode multiple frames into the extra capacity of the output vector.
2864    ///
2865    /// `input` must contain an exact number of frames.
2866    ///
2867    /// `output` must have enough spare capacity to hold the decompressed
2868    /// data. This adds no extra slack: exact-fit output is now eligible
2869    /// for the direct decode path, so a `Vec::with_capacity(fcs)` is
2870    /// decoded straight into without a growth/reallocation. It will NOT
2871    /// grow the vector to fit the decompressed payload itself; the
2872    /// caller's pre-allocated capacity must already cover the data. If
2873    /// you don't know how large the output will be, use
2874    /// [`FrameDecoder::decode_blocks`] instead.
2875    ///
2876    /// This calls [`FrameDecoder::init`], and all bytes currently in the decoder will be lost.
2877    ///
2878    /// The length of the output vector is updated to include the
2879    /// decompressed data. The length is not changed if an error occurs.
2880    pub fn decode_all_to_vec(
2881        &mut self,
2882        input: &[u8],
2883        output: &mut Vec<u8>,
2884    ) -> Result<(), FrameDecoderError> {
2885        let len = output.len();
2886        let cap = output.capacity();
2887        output.resize(cap, 0);
2888        match self.decode_all(input, &mut output[len..]) {
2889            Ok(bytes_written) => {
2890                let new_len = core::cmp::min(len + bytes_written, cap); // Sanitizes `bytes_written`.
2891                output.resize(new_len, 0);
2892                Ok(())
2893            }
2894            Err(e) => {
2895                output.resize(len, 0);
2896                Err(e)
2897            }
2898        }
2899    }
2900
2901    /// Single-frame direct-decode path. Decodes one zstd frame into
2902    /// `output[..content_size]` via a stack-local
2903    /// `DecodeBuffer<UserSliceBackend>`, bypassing the per-block
2904    /// FlatBuf/Ring -> `read()` drain copy.
2905    ///
2906    /// # Preconditions (caller-enforced)
2907    ///
2908    /// - `self.init` (or `init_with_dict_handle`) was called for
2909    ///   this frame so `self.state` is populated.
2910    /// - `content_size` matches `self.state.frame_header
2911    ///   .frame_content_size()` and is `> 0` (caller already passed
2912    ///   the eligibility gate).
2913    /// - `output.len() >= content_size`. No `WILDCOPY_OVERLENGTH`
2914    ///   trailing slack is required: the trailing sequence(s) take the
2915    ///   bounded (non-overshooting) copy in
2916    ///   [`UserSliceBackend::exec_sequence_bounded`].
2917    ///
2918    /// Dictionary frames are supported: the scratch buffer's shared
2919    /// dict handle is forwarded to the stack-local `DecodeBuffer`, so
2920    /// offsets reaching past the frame's own output resolve through
2921    /// `repeat_from_dict` (the ext-dict slow path).
2922    ///
2923    /// On return, `input` points at the byte immediately after the
2924    /// frame's checksum (or after the last block, when the frame
2925    /// has `content_checksum_flag = 0`). `self.state.frame_finished`
2926    /// is set so [`Self::is_finished`] reports `true`.
2927    fn run_direct_decode(
2928        &mut self,
2929        input: &mut &[u8],
2930        output: &mut [u8],
2931        content_size: u64,
2932    ) -> Result<usize, FrameDecoderError> {
2933        #[cfg(test)]
2934        {
2935            self.direct_frames += 1;
2936        }
2937        use super::block_decoder;
2938        use super::decode_buffer::DecodeBuffer;
2939        use super::scratch::DirectScratch;
2940        use super::user_slice_buf::UserSliceBackend;
2941        use crate::io::Read;
2942        use FrameDecoderError as err;
2943
2944        let state = self
2945            .state
2946            .as_mut()
2947            .expect("caller ensures init populated state");
2948
2949        // Borrow persistent fields out of whichever scratch variant
2950        // `init` produced (Flat for single_segment, Ring for
2951        // multi-segment) — both expose the same HUF/FSE/Vec
2952        // fields; only `buffer` differs and we don't use that here.
2953        // Macro-style binding avoids the closure / generic
2954        // gymnastics of returning multiple `&mut` from a match arm.
2955        // Resolve the dictionary borrow for this frame BEFORE taking the
2956        // `&mut` field borrows below — `active_dict` is a disjoint field, so
2957        // the shared borrow coexists with the mutable scratch borrows. It is
2958        // threaded as a call-scoped argument into every `Dict`-sourced read
2959        // (the direct path's `repeat_from_dict` ext-dict slow path), mirroring
2960        // C's per-frame pointer hand-off with zero refcount churn.
2961        // Only expose the held dictionary while THIS frame is dict-backed
2962        // (`using_dict` is set per dict-apply, cleared on reset). A reused
2963        // decoder keeps `active_dict` across a no-dict frame for the
2964        // `ptr::eq` reuse-skip, so it must be gated here or a stray
2965        // out-of-window offset on a dictless frame would resolve against the
2966        // stale dictionary content instead of erroring.
2967        let dict_ref = if state.using_dict.is_some() {
2968            state.active_dict.as_ref().map(|h| h.as_dict())
2969        } else {
2970            None
2971        };
2972        let (huf, fse, offset_hist, literals_buffer, block_content_buffer, window_size) =
2973            match &mut state.decoder_scratch {
2974                DecoderScratchKind::Flat(s) => (
2975                    &mut s.huf,
2976                    &mut s.fse,
2977                    &mut s.offset_hist,
2978                    &mut s.literals_buffer,
2979                    &mut s.block_content_buffer,
2980                    s.buffer.window_size,
2981                ),
2982                DecoderScratchKind::Ring(s) => (
2983                    &mut s.huf,
2984                    &mut s.fse,
2985                    &mut s.offset_hist,
2986                    &mut s.literals_buffer,
2987                    &mut s.block_content_buffer,
2988                    s.buffer.window_size,
2989                ),
2990            };
2991        let backend = UserSliceBackend::from_slice(output);
2992        let buffer = DecodeBuffer::from_backend(backend, window_size);
2993        let mut direct = DirectScratch {
2994            huf,
2995            fse,
2996            offset_hist,
2997            literals_buffer,
2998            block_content_buffer,
2999            buffer,
3000        };
3001
3002        // Block loop. Mirrors `decode_blocks` (without the
3003        // strategy-bounded early exit — we always decode the whole
3004        // frame in one shot for the direct path). Keeps
3005        // `state.bytes_read_counter` / `state.block_counter` in
3006        // sync with `decode_blocks` so post-call accessors
3007        // (`bytes_read_from_source`, `blocks_decoded`) return
3008        // accurate values.
3009        let mut block_dec = block_decoder::new();
3010        // Track total output bytes against the declared
3011        // `frame_content_size` via the buffer's actual write
3012        // counter — `BlockHeader.decompressed_size` is 0 for
3013        // Compressed blocks (the header parser can't know the
3014        // expanded size before decoding the body), so per-header
3015        // tracking would always count 0 for those blocks and
3016        // miscount frames that aren't pure Raw/RLE.
3017        let mut produced: u64 = 0;
3018        // Per-block output ranges captured during the direct-path
3019        // loop. After the loop we re-borrow `output` (post-drop of
3020        // `direct`) and XXH64 each range into
3021        // `self.computed_block_checksums`, so the digests vector
3022        // stays consistent with the legacy `decode_blocks` path
3023        // regardless of which dispatch the frame took.
3024        // `Vec::new()` does not allocate, so this stays free when
3025        // `per_block_checksums_enabled` is false: the `push` and the
3026        // post-loop hashing loop are both gated by the same flag.
3027        #[cfg(all(feature = "lsm", feature = "hash"))]
3028        let mut block_ranges: alloc::vec::Vec<(usize, usize)> = alloc::vec::Vec::new();
3029        // Frame-level XXH64, accumulated PER BLOCK right after each block
3030        // decodes — the bytes are still cache-resident then. The previous
3031        // shape hashed the whole output once after the loop, which re-read
3032        // the entire frame cold: a full extra memory pass that the
3033        // reference implementation does not make (it hashes incrementally
3034        // per block). Invisible on outputs that fit L3, ~1.14x wall on a
3035        // 100 MiB all-raw decode and the dominant CI gap on
3036        // bandwidth-limited hosts.
3037        #[cfg(feature = "hash")]
3038        let mut running_hash: Option<twox_hash::XxHash64> =
3039            if state.frame_header.descriptor.content_checksum_flag()
3040                && self.content_checksum != ContentChecksum::None
3041            {
3042                Some(twox_hash::XxHash64::with_seed(0))
3043            } else {
3044                None
3045            };
3046        loop {
3047            #[cfg(all(feature = "lsm", feature = "hash"))]
3048            let produced_before: Option<usize> = if self.per_block_checksums_enabled {
3049                Some(produced as usize)
3050            } else {
3051                None
3052            };
3053            // Failing-block coordinates captured before the header read (see
3054            // the `decode_blocks` loop for the rationale).
3055            let block_index = state.block_counter as u32;
3056            let block_frame_offset = state.bytes_read_counter as u32;
3057            let (block_header, hsize) =
3058                block_dec.read_block_header(&mut *input).map_err(|source| {
3059                    block_header_decode_error(source, block_index, block_frame_offset)
3060                })?;
3061            state.bytes_read_counter += u64::from(hsize);
3062            // Pre-flight FCS check ONLY for Raw / RLE blocks where
3063            // `decompressed_size` is the actual block output size.
3064            // For Compressed blocks the header field is 0; the
3065            // post-decode check below catches overflow via the
3066            // backend's actual write counter delta.
3067            let block_upper = u64::from(block_header.decompressed_size);
3068            if block_upper > 0 && produced + block_upper > content_size {
3069                // Frame is corrupt — Raw/RLE block headers claim
3070                // more output than the FCS allows.
3071                return Err(err::FrameContentSizeMismatch {
3072                    declared: content_size,
3073                    produced: produced + block_upper,
3074                });
3075            }
3076            // Slice-source fast path: consume the block body
3077            // straight from `input` without copying into the
3078            // persistent `block_content_buffer`.
3079            let body_consumed = match block_dec.decode_block_content_from_slice(
3080                &block_header,
3081                &mut direct,
3082                dict_ref,
3083                &mut *input,
3084            ) {
3085                Ok(n) => n,
3086                // Defense-in-depth: RLE / Raw block whose declared
3087                // `decompressed_size` slipped past the per-block
3088                // pre-flight above and tripped the backend's
3089                // fallible write surface.
3090                Err(crate::decoding::errors::DecodeBlockContentError::BackendOverflow {
3091                    ..
3092                }) => {
3093                    // Use saturating_add on the
3094                    // `produced + decompressed_size` sum. Each block
3095                    // is bounded by 128 KiB (MAX_BLOCK_SIZE), but
3096                    // accumulated `produced` can grow toward
3097                    // u64::MAX across adversarial frames. Saturating
3098                    // avoids a panic on the error path itself.
3099                    return Err(err::FrameContentSizeMismatch {
3100                        declared: content_size,
3101                        produced: produced
3102                            .saturating_add(u64::from(block_header.decompressed_size)),
3103                    });
3104                }
3105                // Compressed-block in-block overshoot: the sequence
3106                // executor (upstream zstd-inline path) or the match-repeat
3107                // fallback tripped the fixed-capacity backend's per-write
3108                // check. Unlike Raw/RLE, a Compressed block carries no
3109                // header-declared output size, so `produced` is computed
3110                // from the partial fill: `tail` bytes were written before
3111                // the failing op, and `requested` is what overflowed —
3112                // their sum is a strict lower bound on the frame's true
3113                // expanded size and is always > `content_size` (the
3114                // direct path is only entered when the slice is sized to
3115                // `content_size + WILDCOPY_OVERLENGTH`, so any overflow
3116                // means the frame exceeded the declared FCS, never a
3117                // caller-undersized buffer). Folds into the same
3118                // `FrameContentSizeMismatch` contract as Raw/RLE.
3119                Err(crate::decoding::errors::DecodeBlockContentError::DecompressBlockError(
3120                    crate::decoding::errors::DecompressBlockError::ExecuteSequencesError(ref e),
3121                )) if e.output_overflow_requested().is_some() => {
3122                    let requested = e
3123                        .output_overflow_requested()
3124                        .expect("guard guarantees Some") as u64;
3125                    let tail = direct.buffer.buffer_ref().tail() as u64;
3126                    return Err(err::FrameContentSizeMismatch {
3127                        declared: content_size,
3128                        produced: tail.saturating_add(requested),
3129                    });
3130                }
3131                Err(e) => {
3132                    return Err(block_body_decode_error(
3133                        e,
3134                        block_index,
3135                        block_frame_offset,
3136                        &block_header,
3137                        hsize,
3138                    ));
3139                }
3140            };
3141            // Hash this block's freshly-written bytes while they are hot
3142            // (see `running_hash` above). `tail()` is the physical write
3143            // cursor: `drop_to_window_size` below only advances the head,
3144            // so `[prev_tail, tail)` is exactly this block's output.
3145            #[cfg(feature = "hash")]
3146            if let Some(hasher) = running_hash.as_mut() {
3147                use core::hash::Hasher;
3148                hasher.write(direct.buffer.buffer_ref().written_since(produced as usize));
3149            }
3150            produced = direct.buffer.buffer_ref().tail() as u64;
3151            // Post-decode FCS overflow check.
3152            if produced > content_size {
3153                return Err(err::FrameContentSizeMismatch {
3154                    declared: content_size,
3155                    produced,
3156                });
3157            }
3158            state.bytes_read_counter += body_consumed;
3159            state.block_counter += 1;
3160            #[cfg(all(feature = "lsm", feature = "hash"))]
3161            if let Some(produced_before) = produced_before {
3162                block_ranges.push((produced_before, produced as usize));
3163            }
3164            // Cap the visible buffer at window_size between blocks
3165            // so the next block's match-offset validation matches
3166            // the spec's `offset <= window_size` rule.
3167            direct.buffer.drop_to_window_size();
3168            if block_header.last_block {
3169                if state.frame_header.descriptor.content_checksum_flag() {
3170                    let mut chksum = [0u8; 4];
3171                    input
3172                        .read_exact(&mut chksum)
3173                        .map_err(err::FailedToReadChecksum)?;
3174                    state.bytes_read_counter += 4;
3175                    state.check_sum = Some(u32::from_le_bytes(chksum));
3176                }
3177                break;
3178            }
3179        }
3180        // Final sanity: blocks summed to exactly `content_size`.
3181        if produced != content_size {
3182            return Err(err::FrameContentSizeMismatch {
3183                declared: content_size,
3184                produced,
3185            });
3186        }
3187
3188        let written = content_size as usize;
3189        state.frame_finished = true;
3190        // `direct`'s last use is in the decode loop above; NLL therefore
3191        // releases its `&mut output` borrow before here, freeing `output` for
3192        // the hash re-borrow below. No explicit `drop(direct)` is needed:
3193        // `DirectScratch` now holds only borrowed dict POINTERS (not an owned
3194        // `Arc`), so it is not a `Drop` type whose glue would hold the borrow
3195        // to end-of-scope.
3196        // Per-block XXH64 (low 32 bits) over the captured ranges.
3197        // Mirrors `decode_blocks`' per-block hashing so the digests
3198        // vector stays identical regardless of which dispatch path
3199        // the frame took. Ranges were recorded inside the loop while
3200        // `direct` held a mutable borrow on `output`; now that the
3201        // borrow is dropped we can read the slices directly.
3202        #[cfg(all(feature = "lsm", feature = "hash"))]
3203        if self.per_block_checksums_enabled {
3204            use core::hash::Hasher;
3205            for (start, end) in &block_ranges {
3206                let mut h = twox_hash::XxHash64::with_seed(0);
3207                h.write(&output[*start..*end]);
3208                self.computed_block_checksums.push(h.finish() as u32);
3209            }
3210        }
3211        #[cfg(feature = "hash")]
3212        if let Some(hasher) = running_hash {
3213            // Propagate the per-block-accumulated hasher state (see the
3214            // `running_hash` rationale above the loop) so the frame-tail
3215            // XXH64 check and `get_calculated_checksum()` read the digest.
3216            // `running_hash` is `None` for flag-off frames or
3217            // `ContentChecksum::None` — nothing to verify there, and
3218            // `get_calculated_checksum()` returns `None`, matching the skip.
3219            match &mut state.decoder_scratch {
3220                DecoderScratchKind::Flat(s) => s.buffer.hash = hasher,
3221                DecoderScratchKind::Ring(s) => s.buffer.hash = hasher,
3222            }
3223        }
3224        Ok(written)
3225    }
3226}
3227
3228/// Read bytes from the decode_buffer that are no longer needed. While the frame is not yet finished
3229/// this will retain window_size bytes, else it will drain it completely
3230impl Read for FrameDecoder {
3231    fn read(&mut self, target: &mut [u8]) -> Result<usize, Error> {
3232        let state = match &mut self.state {
3233            None => return Ok(0),
3234            Some(s) => s,
3235        };
3236        if state.frame_finished {
3237            state.decoder_scratch.buffer_read_all(target)
3238        } else {
3239            state.decoder_scratch.buffer_read(target)
3240        }
3241    }
3242}
3243
3244#[cfg(test)]
3245mod tests;