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, [`Self::init`] / [`Self::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 /// Best kernel this CPU offers, resolved once per decoder rather than per
207 /// block decoder built. A chunked decode enters `decode_from_to` once per
208 /// caller-sized target, so detecting there put an atomic read and a branch
209 /// on every call; feature detection belongs before the work, not inside it.
210 kernel: crate::cpu_kernel::CpuKernelTag,
211}
212
213/// How the decoder treats a frame's optional XXH64 content checksum
214/// (RFC 8878 Content_Checksum_flag). The XXH64 pass over the decompressed
215/// output is a measurable share of decode time, so it is made skippable.
216///
217/// ```
218/// use structured_zstd::decoding::{ContentChecksum, FrameDecoder};
219/// let mut decoder = FrameDecoder::new();
220/// decoder.set_content_checksum(ContentChecksum::Verify);
221/// ```
222#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
223pub enum ContentChecksum {
224 /// Skip the XXH64 pass entirely: no compute, no verify.
225 /// `get_calculated_checksum()` returns `None`.
226 None,
227 /// Compute the checksum and expose it via the accessors, but do not
228 /// error on a mismatch. This is the default and matches the historical
229 /// behaviour (callers verify manually if they wish).
230 #[default]
231 EmitOnly,
232 /// Compute the checksum and compare it against the frame's stored value;
233 /// a disagreement fails the decode with
234 /// [`FrameDecoderError::ChecksumMismatch`].
235 /// Without the `hash` feature there is no way to compute a digest, so
236 /// `Verify` cannot detect a mismatch and behaves like `None`.
237 Verify,
238}
239
240/// Decode-relevant identity of a frame, used to reject a [`ResumeState`]
241/// captured from one frame being applied to a frame of a different shape. Covers
242/// every header field that changes how blocks decode (buffer sizing, backend
243/// kind, entropy/dictionary context, trailing-checksum handling, declared
244/// content size, magicless framing).
245///
246/// This is a SHAPE guard, not a content-unique fingerprint: two distinct frames
247/// that happen to share all these header fields produce the same key (no cheap
248/// header field uniquely identifies frame content). It catches the realistic
249/// accidental misuse — applying a snapshot to a frame with a different
250/// window/dictionary/size — with a typed error instead of byte-wrong output.
251/// Pairing a `ResumeState` with the correct frame's compressed source and
252/// `window_prime` remains the caller's contract.
253#[cfg(feature = "lsm")]
254#[derive(Clone, Copy, PartialEq, Eq, Debug)]
255struct FrameKey {
256 window_size: u64,
257 frame_content_size: u64,
258 /// `Dictionary_ID` declared in the frame header (`None` when omitted).
259 dictionary_id: Option<u32>,
260 /// Dictionary actually applied to the decoder (`state.using_dict`). This is
261 /// distinct from `dictionary_id`: a frame with a dictless header can still
262 /// be decoded with an explicit dictionary via `reset_with_dict_handle` /
263 /// `force_dict`, and two such decodes with different dictionaries must NOT
264 /// compare equal — keying only on the header field would miss that.
265 active_dictionary_id: Option<u32>,
266 single_segment: bool,
267 content_checksum: bool,
268 magicless: bool,
269}
270
271#[cfg(feature = "lsm")]
272impl FrameKey {
273 fn from_state(state: &FrameDecoderState, magicless: bool) -> FrameKey {
274 let header = &state.frame_header;
275 FrameKey {
276 window_size: header.window_size().unwrap_or(0),
277 frame_content_size: header.frame_content_size(),
278 dictionary_id: header.dictionary_id(),
279 active_dictionary_id: state.using_dict,
280 single_segment: header.descriptor.single_segment_flag(),
281 content_checksum: header.descriptor.content_checksum_flag(),
282 magicless,
283 }
284 }
285}
286
287/// XXH64 of a contiguous byte slice — the resume-side counterpart to
288/// [`DecoderScratchKind::window_tail_hash`]. Streaming XXH64 is chunk-boundary
289/// independent, so this single-slice hash equals the emit-side two-slice hash
290/// over the same bytes.
291#[cfg(all(feature = "lsm", feature = "hash"))]
292fn xxh64_of(bytes: &[u8]) -> u64 {
293 use core::hash::Hasher;
294 let mut h = twox_hash::XxHash64::with_seed(0);
295 h.write(bytes);
296 h.finish()
297}
298
299/// Cross-block decode state needed to resume a cold partial decode at an inner
300/// block boundary, emitted by [`FrameDecoder::decode_blocks_partial`] when its
301/// `emit_resume` argument is `true` (returned in
302/// [`PartialDecode::resume_state`]) and fed back via that same method's
303/// [`resume`](FrameDecoder::decode_blocks_partial) argument
304/// ([`ResumeInput`]).
305///
306/// A zstd block does not carry all the state required to decode it in
307/// isolation: besides the shared match window (the decompressed output history),
308/// a Compressed block may reuse the previous block's entropy tables via
309/// `Repeat_Mode` (literals Huffman + the LL/OF/ML FSE distributions) and always
310/// continues the running repeat-offset history. This snapshot carries exactly
311/// that carry-over state plus the resume coordinates, so resuming is
312/// byte-identical to a contiguous decode even across a dropped decoder. The
313/// window itself is NOT stored here — the caller supplies it back through
314/// [`ResumeInput::window_prime`] from the decompressed output it already
315/// persists. Neither is the dictionary: for a dictionary frame the caller
316/// re-attaches it to the resuming decoder via [`FrameDecoder::reset`] /
317/// [`FrameDecoder::reset_with_dict_handle`] (it already holds the dictionary
318/// from encode time), and the snapshot records only the dictionary's identity
319/// so a resume under a different dictionary is rejected.
320///
321/// Behind the `lsm` Cargo feature.
322#[cfg(feature = "lsm")]
323#[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
324pub struct ResumeState {
325 /// Identity of the frame this state was captured from. Compared against the
326 /// frame currently reset into the decoder before any state is restored, so a
327 /// snapshot from a different frame shape is rejected with
328 /// [`FrameDecoderError::ResumeFrameMismatch`] instead of silently producing
329 /// byte-wrong output.
330 frame_key: FrameKey,
331 /// Index of the block to resume AT (the first block NOT yet decoded).
332 block_index: u32,
333 /// Cumulative decompressed byte count produced before `block_index`.
334 output_offset: u64,
335 /// FSE tables (LL/OF/ML) as of the last decoded block — the source for a
336 /// `Repeat_Mode` resume block.
337 fse: crate::decoding::scratch::FSEScratch,
338 /// Huffman literals table as of the last decoded block — the source for a
339 /// treeless (repeat) literals resume block.
340 huf: crate::decoding::scratch::HuffmanScratch,
341 /// Running repeat-offset history (`offset_hist`) as of the last decoded
342 /// block.
343 offset_hist: [u32; 3],
344 /// XXH64 of the exact window-prime bytes (the last `min(window_size,
345 /// output_offset)` decompressed bytes) captured at emit. Verified at resume
346 /// against the caller-supplied [`ResumeInput::window_prime`]: a content
347 /// mismatch (wrong frame, wrong or corrupted prime) is a near-unique
348 /// (≈2⁻⁶⁴) signal and is rejected with
349 /// [`FrameDecoderError::ResumeFrameMismatch`]. This is the content-exact
350 /// guard; [`FrameKey`] is the cheap shape pre-check that works without the
351 /// `hash` feature. Behind `all(lsm, hash)`.
352 #[cfg(feature = "hash")]
353 window_hash: u64,
354}
355
356#[cfg(feature = "lsm")]
357impl ResumeState {
358 /// Inner block index this state resumes at (the first block not yet
359 /// decoded). Pass it as the `end_block` lower bound (and as `start_block`)
360 /// of the resuming
361 /// [`decode_blocks_partial`](FrameDecoder::decode_blocks_partial) call.
362 pub fn block_index(&self) -> u32 {
363 self.block_index
364 }
365
366 /// Cumulative decompressed byte count produced before
367 /// [`block_index`](Self::block_index) — i.e. the decompressed offset at
368 /// which the resumed output begins. Equals
369 /// `FrameEmitInfo::decompressed_byte_range(block_index).start`. Use it to
370 /// slice the `window_prime` tail the resumed call needs.
371 pub fn output_offset(&self) -> u64 {
372 self.output_offset
373 }
374}
375
376// Manual Debug: the entropy tables are large internal scratch with no useful
377// Debug surface; only the resume coordinates are worth printing (and this lets
378// `PartialDecode` keep its derived Debug).
379#[cfg(feature = "lsm")]
380impl core::fmt::Debug for ResumeState {
381 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
382 f.debug_struct("ResumeState")
383 .field("block_index", &self.block_index)
384 .field("output_offset", &self.output_offset)
385 .finish_non_exhaustive()
386 }
387}
388
389/// Resume input fed to [`FrameDecoder::decode_blocks_partial`]'s `resume`
390/// argument to continue a cold partial decode without re-decompressing the
391/// preceding blocks.
392///
393/// Behind the `lsm` Cargo feature.
394#[cfg(feature = "lsm")]
395#[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
396pub struct ResumeInput<'a> {
397 /// The caller's already-decompressed output ending just before
398 /// [`ResumeState::block_index`]. Must contain at least the last
399 /// `min(window_size, output_offset)` bytes (a full match window, or the
400 /// whole prefix when it is shorter than one window); anything beyond the
401 /// last `window_size` bytes is ignored, so passing the entire prefix is
402 /// also valid (capped internally, bounding resume memory to one window).
403 pub window_prime: &'a [u8],
404 /// Cross-block entropy/repcode state emitted by the prior
405 /// [`decode_blocks_partial`](FrameDecoder::decode_blocks_partial) call.
406 pub state: &'a ResumeState,
407}
408
409/// Backend-tagged decode scratch — chosen at frame-reset time based
410/// on the parsed `FrameHeader.descriptor.single_segment_flag()` and
411/// kept stable through the lifetime of the frame. The match in each
412/// helper below dispatches **once per call** (e.g. once per block in
413/// `decode_block_content`, once per drain in `drain_to_writer`) —
414/// never inside the hot push/repeat loop, which is fully
415/// monomorphised through the `DecoderScratch<B>` generic.
416enum DecoderScratchKind {
417 Ring(DecoderScratch<RingBuffer>),
418 Flat(DecoderScratch<FlatBuf>),
419}
420
421impl DecoderScratchKind {
422 fn new_ring(window_size: usize) -> Self {
423 // Lazy ring-buffer allocation: do NOT `reserve(window_size)` here.
424 // The direct-decode path (`run_direct_decode`) writes through
425 // `UserSliceBackend` and never touches the ring; allocating it
426 // eagerly wastes one full window of peak memory on the common
427 // direct-eligible frame. On the non-direct path the window is
428 // pre-reserved once at frame entry (`decode_all_impl` and
429 // `decode_blocks` both call `DecoderScratchKind::reserve_buffer`
430 // before any block writes), so multi-block frames pay one
431 // amortised grow instead of repeated `reserve_amortized` steps
432 // per block. Issue #279 round 2.
433 let s = DecoderScratch::<RingBuffer>::new(window_size);
434 Self::Ring(s)
435 }
436
437 /// Construct a flat-backed scratch for a single-segment frame.
438 /// `frame_content_size` is the upcoming output size in bytes
439 /// (== `window_size` when the flag is set).
440 ///
441 /// Lazy buffer allocation (mirrors [`Self::new_ring`]): do NOT
442 /// pre-size the `FlatBuf`. The direct-decode path
443 /// (`run_direct_decode`) writes through `UserSliceBackend` and never
444 /// touches this buffer, so eagerly allocating a full FCS wastes one
445 /// whole content-size of peak memory on the common direct-eligible
446 /// single-segment frame. The non-direct fallback reserves it once via
447 /// `reserve_buffer(window_size)` at frame entry before any block
448 /// write (`FlatBuf::reserve` adds the `WILDCOPY_OVERLENGTH` slack),
449 /// and every inline-exec site (trait method and per-kernel macros)
450 /// now carries a tight-tail bounded copy, so a tight buffer can never
451 /// overshoot regardless of construction-time slack.
452 fn new_flat(frame_content_size: usize) -> Self {
453 let s = DecoderScratch::<FlatBuf>::new(frame_content_size);
454 Self::Flat(s)
455 }
456
457 /// Reset (or transition between) backends for a new frame.
458 /// Reuses the existing `DecoderScratch` allocations (FSE / HUF
459 /// tables, sequence vec, etc.) when the backend kind is unchanged
460 /// — only the underlying buffer is re-sized for the new frame.
461 /// Building a fresh `DecoderScratch` on every frame would
462 /// re-allocate everything and was measured at +255 % vs ring on
463 /// small frames; reusing it keeps the small-frame cost flat.
464 fn reset(&mut self, frame: &frame::FrameHeader, window_size: usize) {
465 if frame.descriptor.single_segment_flag() {
466 match self {
467 Self::Flat(s) => {
468 s.reset(window_size);
469 // `DecoderScratch::reset` clears the backing buffer and
470 // updates `window_size` WITHOUT reserving it (it may still
471 // resize the per-block scratch Vecs up to
472 // `min(window_size, MAX_BLOCK_SIZE)`). Backing-buffer
473 // capacity is decided one layer up: direct-eligible frames
474 // never touch it, and the non-direct path pre-reserves once
475 // via `reserve_buffer(window_size)` at frame entry.
476 }
477 Self::Ring(_) => *self = Self::new_flat(window_size),
478 }
479 } else {
480 match self {
481 Self::Ring(s) => s.reset(window_size),
482 Self::Flat(_) => *self = Self::new_ring(window_size),
483 }
484 }
485 }
486
487 fn init_from_dict(&mut self, dict: &DictionaryHandle) {
488 match self {
489 Self::Ring(s) => s.init_from_dict(dict),
490 Self::Flat(s) => s.init_from_dict(dict),
491 }
492 }
493
494 #[inline]
495 fn buffer_len(&self) -> usize {
496 match self {
497 Self::Ring(s) => s.buffer.len(),
498 Self::Flat(s) => s.buffer.len(),
499 }
500 }
501
502 fn workspace_bytes(&self) -> usize {
503 match self {
504 Self::Ring(s) => s.workspace_bytes(),
505 Self::Flat(s) => s.workspace_bytes(),
506 }
507 }
508
509 /// Pre-reserve the backing buffer to `window_size` in a single
510 /// allocation. Called once on the non-direct (`decode_blocks`) path
511 /// after direct-eligibility is ruled out, so multi-segment fallback
512 /// decodes don't pay repeated `reserve_amortized` grow steps
513 /// (128 KiB → 256 KiB → ... → window) as blocks accumulate.
514 ///
515 /// Direct-eligible frames never call this and pay zero backing-buffer
516 /// allocation for the window, on BOTH backends: `new_ring` and
517 /// `new_flat` are each lazy (no pre-reserve), so a direct-eligible
518 /// frame writes only through `UserSliceBackend` and leaves this
519 /// buffer empty.
520 ///
521 /// `target` is the TARGET buffer capacity (`decoding_buffer_size`) and
522 /// `growth_limit` the most later growth may reach
523 /// (`decoding_buffer_limit`); the method itself computes the shortfall
524 /// past the bytes already buffered before calling the backend's
525 /// ADDITIONAL-semantics `reserve_exact`. That keeps re-entries (the
526 /// decode_all fallback loop runs `decode_blocks` once per strategy
527 /// chunk, and streaming callers invoke it per call) from growing a
528 /// window-full buffer toward 2x window, while per-block growth keeps
529 /// the amortized `reserve`.
530 /// Hand the buffer what the frame declared it would produce, so the
531 /// per-block reservation can stop at the frame's remainder.
532 #[inline]
533 fn set_declared_content(&mut self, content_size: Option<u64>) {
534 match self {
535 Self::Ring(s) => s.buffer.set_declared_content(content_size),
536 Self::Flat(s) => s.buffer.set_declared_content(content_size),
537 }
538 }
539
540 #[inline]
541 fn reserve_buffer(&mut self, target: usize, growth_limit: usize) {
542 let window_size = target;
543 // Exact growth: this is the one-shot pre-reservation, and a request
544 // landing one slack past the retained capacity (e.g. a dictionary
545 // prefix already loaded into the buffer) must not DOUBLE a
546 // window-sized allocation through the amortized policy. Per-block
547 // growth keeps the amortized `reserve`.
548 //
549 // `reserve_exact` takes ADDITIONAL capacity, so request only the
550 // shortfall past the bytes already buffered: the decode_all
551 // fallback loop re-enters `decode_blocks` once per strategy chunk,
552 // and re-requesting the full window each iteration would grow a
553 // window-sized buffer toward 2x window.
554 match self {
555 Self::Ring(s) => {
556 // The ring's growth rounds to the next power of two, capped at
557 // its limit; with the limit at the target for this one-shot
558 // reservation it lands exactly there, and later growth (a
559 // compressed block's own reservation) may then reach the
560 // frame's real limit, never double past it.
561 s.buffer.set_growth_limit(window_size);
562 let additional = window_size.saturating_sub(s.buffer.len());
563 s.buffer.reserve_exact(additional);
564 s.buffer.set_growth_limit(growth_limit);
565 }
566 Self::Flat(s) => {
567 let additional = window_size.saturating_sub(s.buffer.len());
568 s.buffer.reserve_exact(additional);
569 }
570 }
571 }
572
573 /// Last `n` bytes of the visible buffer as `(s1, s2)` (wrap-aware).
574 /// Routes through whichever backend the current scratch holds.
575 #[cfg(all(feature = "lsm", feature = "hash"))]
576 fn last_n_as_slices(&self, n: usize) -> (&[u8], &[u8]) {
577 match self {
578 Self::Ring(s) => s.buffer.last_n_as_slices(n),
579 Self::Flat(s) => s.buffer.last_n_as_slices(n),
580 }
581 }
582
583 fn buffer_drain(&mut self) -> Vec<u8> {
584 match self {
585 Self::Ring(s) => s.buffer.drain(),
586 Self::Flat(s) => s.buffer.drain(),
587 }
588 }
589
590 fn buffer_drain_to_window_size(&mut self) -> Option<Vec<u8>> {
591 match self {
592 Self::Ring(s) => s.buffer.drain_to_window_size(),
593 Self::Flat(s) => s.buffer.drain_to_window_size(),
594 }
595 }
596
597 fn buffer_drain_to_writer(&mut self, sink: impl Write) -> Result<usize, Error> {
598 match self {
599 Self::Ring(s) => s.buffer.drain_to_writer(sink),
600 Self::Flat(s) => s.buffer.drain_to_writer(sink),
601 }
602 }
603
604 fn buffer_drain_to_window_size_writer(&mut self, sink: impl Write) -> Result<usize, Error> {
605 match self {
606 Self::Ring(s) => s.buffer.drain_to_window_size_writer(sink),
607 Self::Flat(s) => s.buffer.drain_to_window_size_writer(sink),
608 }
609 }
610
611 fn buffer_can_drain(&self) -> usize {
612 match self {
613 Self::Ring(s) => s.buffer.can_drain(),
614 Self::Flat(s) => s.buffer.can_drain(),
615 }
616 }
617
618 fn buffer_can_drain_to_window_size(&self) -> Option<usize> {
619 match self {
620 Self::Ring(s) => s.buffer.can_drain_to_window_size(),
621 Self::Flat(s) => s.buffer.can_drain_to_window_size(),
622 }
623 }
624
625 fn buffer_read(&mut self, target: &mut [u8]) -> Result<usize, Error> {
626 match self {
627 Self::Ring(s) => s.buffer.read(target),
628 Self::Flat(s) => s.buffer.read(target),
629 }
630 }
631
632 /// [`Self::buffer_read`], also reporting the drainable bytes `target` had
633 /// no room for.
634 fn buffer_read_reporting_pending(
635 &mut self,
636 target: &mut [u8],
637 ) -> Result<(usize, usize), Error> {
638 match self {
639 Self::Ring(s) => s.buffer.read_reporting_pending(target),
640 Self::Flat(s) => s.buffer.read_reporting_pending(target),
641 }
642 }
643
644 fn buffer_read_all(&mut self, target: &mut [u8]) -> Result<usize, Error> {
645 match self {
646 Self::Ring(s) => s.buffer.read_all(target),
647 Self::Flat(s) => s.buffer.read_all(target),
648 }
649 }
650
651 /// Drop visible output beyond `window_size` without producing it,
652 /// keeping the most recent `window_size` bytes available to back
653 /// future match copies. Used by `decode_blocks_partial` to bound
654 /// memory while decoding the leading (skipped) blocks into the window.
655 #[cfg(feature = "lsm")]
656 fn buffer_drop_to_window_size(&mut self) -> usize {
657 match self {
658 Self::Ring(s) => s.buffer.drop_to_window_size(),
659 Self::Flat(s) => s.buffer.drop_to_window_size(),
660 }
661 }
662
663 /// Drop exactly `n` bytes from the front of the visible output without
664 /// producing them. Used by `decode_blocks_partial` to discard the
665 /// leading blocks' window-context bytes once the in-range blocks are
666 /// decoded (match resolution complete), leaving only the in-range output.
667 #[cfg(feature = "lsm")]
668 fn buffer_discard_front(&mut self, n: usize) {
669 match self {
670 Self::Ring(s) => s.buffer.discard_front(n),
671 Self::Flat(s) => s.buffer.discard_front(n),
672 }
673 }
674
675 /// Prime the match window with the caller's already-decompressed tail for
676 /// a resumed partial decode. Routes through whichever backend the current
677 /// scratch holds. See
678 /// [`DecodeBuffer::prime_window`](crate::decoding::decode_buffer::DecodeBuffer::prime_window).
679 #[cfg(feature = "lsm")]
680 fn prime_window(
681 &mut self,
682 prefix: &[u8],
683 total_output: u64,
684 kernel: crate::cpu_kernel::CpuKernelTag,
685 ) {
686 match self {
687 Self::Ring(s) => s.buffer.prime_window(prefix, total_output, kernel),
688 Self::Flat(s) => s.buffer.prime_window(prefix, total_output, kernel),
689 }
690 }
691
692 /// Total decompressed bytes produced so far (the buffer's running output
693 /// counter, unaffected by window drops / drains): the frame's length once
694 /// its last block is decoded, and a captured resume state's offset.
695 fn total_output(&self) -> u64 {
696 match self {
697 Self::Ring(s) => s.buffer.total_output(),
698 Self::Flat(s) => s.buffer.total_output(),
699 }
700 }
701
702 /// Set the output counter to the length of a frame the direct path decoded
703 /// into the caller's slice, which never passes through this buffer.
704 fn set_total_output(&mut self, produced: u64) {
705 match self {
706 Self::Ring(s) => s.buffer.set_total_output(produced),
707 Self::Flat(s) => s.buffer.set_total_output(produced),
708 }
709 }
710
711 /// Append `data` to the buffer, copied under the kernel a literals-only
712 /// block takes: the scalar tier stays portable.
713 fn buffer_push(&mut self, data: &[u8], kernel: crate::cpu_kernel::CpuKernelTag) {
714 use crate::cpu_kernel::{BaselineKernel, CpuKernelTag, ScalarKernel};
715 let scalar = kernel == CpuKernelTag::Scalar;
716 match self {
717 Self::Ring(s) if scalar => s.buffer.push::<ScalarKernel>(data),
718 Self::Ring(s) => s.buffer.push::<BaselineKernel>(data),
719 Self::Flat(s) if scalar => s.buffer.push::<ScalarKernel>(data),
720 Self::Flat(s) => s.buffer.push::<BaselineKernel>(data),
721 }
722 }
723
724 /// Clone the cross-block entropy/repcode state (FSE + Huffman tables +
725 /// `offset_hist`) out of the live scratch for a [`ResumeState`] snapshot.
726 #[cfg(feature = "lsm")]
727 fn export_entropy(
728 &self,
729 dict: Option<&crate::decoding::dictionary::Dictionary>,
730 ) -> (
731 crate::decoding::scratch::FSEScratch,
732 crate::decoding::scratch::HuffmanScratch,
733 [u32; 3],
734 ) {
735 let (fse_src, huf_src, offset_hist) = match self {
736 Self::Ring(s) => (&s.fse, &s.huf, s.offset_hist),
737 Self::Flat(s) => (&s.fse, &s.huf, s.offset_hist),
738 };
739 // The live scratch may still be `Dict`-sourced; `reinit_from` /
740 // `reinit_resolved_from` resolve those axes through the borrow into a
741 // self-contained `Local` snapshot, so the dictionary is required here
742 // whenever the captured frame is dict-backed.
743 let mut fse = crate::decoding::scratch::FSEScratch::new();
744 fse.reinit_from(fse_src, dict);
745 let mut huf = crate::decoding::scratch::HuffmanScratch::new();
746 huf.reinit_resolved_from(huf_src, dict);
747 (fse, huf, offset_hist)
748 }
749
750 /// Install entropy/repcode state from a [`ResumeState`] into the live
751 /// scratch so a `Repeat_Mode` / treeless resume block resolves against the
752 /// same tables a contiguous decode would have carried over.
753 #[cfg(feature = "lsm")]
754 fn restore_entropy(&mut self, state: &ResumeState) {
755 // The `ResumeState` snapshot is a self-contained `Local` materialization
756 // (export resolved every Dict axis into local bytes and detached), so no
757 // dictionary borrow is needed to install it back.
758 match self {
759 Self::Ring(s) => {
760 s.fse.reinit_from(&state.fse, None);
761 s.huf.reinit_resolved_from(&state.huf, None);
762 s.offset_hist = state.offset_hist;
763 }
764 Self::Flat(s) => {
765 s.fse.reinit_from(&state.fse, None);
766 s.huf.reinit_resolved_from(&state.huf, None);
767 s.offset_hist = state.offset_hist;
768 }
769 }
770 }
771
772 /// XXH64 of the window-prime bytes for a [`ResumeState`]: the last
773 /// `min(window_size, buffer_len)` bytes of the current buffer, which at emit
774 /// time are exactly the match-window context the resume block will see.
775 /// Wrap-aware via `last_n_as_slices` — streaming XXH64 over the two slices
776 /// equals a single hash over the contiguous `window_prime` at resume.
777 #[cfg(all(feature = "lsm", feature = "hash"))]
778 fn window_tail_hash(&self, window_size: usize) -> u64 {
779 use core::hash::Hasher;
780 let n = core::cmp::min(window_size, self.buffer_len());
781 let (s1, s2) = self.last_n_as_slices(n);
782 let mut h = twox_hash::XxHash64::with_seed(0);
783 h.write(s1);
784 h.write(s2);
785 h.finish()
786 }
787
788 fn decode_block_content<R: Read>(
789 &mut self,
790 decoder: &mut BlockDecoder,
791 header: &crate::blocks::block::BlockHeader,
792 source: R,
793 dict: Option<&crate::decoding::dictionary::Dictionary>,
794 ) -> Result<u64, DecodeBlockContentError> {
795 match self {
796 Self::Ring(s) => decoder.decode_block_content(header, s, dict, source),
797 Self::Flat(s) => decoder.decode_block_content(header, s, dict, source),
798 }
799 }
800
801 /// [`Self::decode_block_content`] for a block whose content is already in
802 /// memory: a compressed block is decoded from `source` in place instead of
803 /// being copied into the block buffer first. Advances `source` past it.
804 fn decode_block_content_from_slice(
805 &mut self,
806 decoder: &mut BlockDecoder,
807 header: &crate::blocks::block::BlockHeader,
808 source: &mut &[u8],
809 dict: Option<&crate::decoding::dictionary::Dictionary>,
810 ) -> Result<u64, DecodeBlockContentError> {
811 match self {
812 Self::Ring(s) => decoder.decode_block_content_from_slice(header, s, dict, source),
813 Self::Flat(s) => decoder.decode_block_content_from_slice(header, s, dict, source),
814 }
815 }
816
817 #[cfg(feature = "hash")]
818 fn hash_finish(&self) -> u64 {
819 use core::hash::Hasher;
820 match self {
821 Self::Ring(s) => s.buffer.hash.finish(),
822 Self::Flat(s) => s.buffer.hash.finish(),
823 }
824 }
825
826 /// Forward the drain-time hash toggle to the inner `DecodeBuffer`
827 /// (streaming path). Called by the frame layer from the decoder's
828 /// `ContentChecksum` mode before each decode.
829 #[cfg(feature = "hash")]
830 fn set_compute_hash(&mut self, compute: bool) {
831 match self {
832 Self::Ring(s) => s.buffer.set_compute_hash(compute),
833 Self::Flat(s) => s.buffer.set_compute_hash(compute),
834 }
835 }
836}
837
838struct FrameDecoderState {
839 pub frame_header: frame::FrameHeader,
840 decoder_scratch: DecoderScratchKind,
841 frame_finished: bool,
842 block_counter: usize,
843 bytes_read_counter: u64,
844 check_sum: Option<u32>,
845 using_dict: Option<u32>,
846 /// The dictionary handle applied to this frame, owned for the frame's whole
847 /// decode so the block loop can hand the scratch a `&Dictionary` borrow at
848 /// every `Dict`-sourced table read. ONE refcount clone per dict-apply (not
849 /// per block, not per frame on the reuse path — the same handle stays held
850 /// across `init_with_dict_handle` -> `decode_blocks`); the decode loop
851 /// borrows from this field (disjoint from `decoder_scratch`) with zero
852 /// further clones. `None` on the no-dict path. Cleared by `reset`.
853 active_dict: Option<DictionaryHandle>,
854}
855
856pub enum BlockDecodingStrategy {
857 All,
858 UptoBlocks(usize),
859 UptoBytes(usize),
860}
861
862/// Outcome of [`FrameDecoder::decode_blocks_partial`]: the decompressed
863/// bytes of the requested inner-block range plus where (if anywhere)
864/// decoding stopped early.
865///
866/// Behind the `lsm` Cargo feature.
867#[cfg(feature = "lsm")]
868#[derive(Debug)]
869pub struct PartialDecode {
870 /// Decompressed bytes of the in-range blocks actually decoded, in
871 /// frame order, as one contiguous buffer. `data.len()` equals the sum
872 /// of the decompressed sizes of blocks `start_block .. start_block +
873 /// blocks_decoded`.
874 pub data: alloc::vec::Vec<u8>,
875 /// First block whose output is in [`data`](Self::data): the requested
876 /// `start_block` on a fresh decode, or [`ResumeState::block_index`] when
877 /// resuming (the caller-supplied `start_block` is ignored in resume mode).
878 pub start_block: u32,
879 /// Number of in-range blocks successfully decoded into
880 /// [`data`](Self::data).
881 pub blocks_decoded: u32,
882 /// `Some((block_index, error))` if decoding stopped on a failing block
883 /// before reaching `end_block` (a corrupt block inside the range, or a
884 /// leading block needed for window context). `None` if the requested
885 /// range decoded cleanly or the frame's last block was reached first.
886 ///
887 /// When the failing block is a leading context block
888 /// (`block_index < start_block`), the in-range window could not be
889 /// built so [`data`](Self::data) is empty and `blocks_decoded` is 0.
890 pub stopped_at: Option<(u32, FrameDecoderError)>,
891 /// `true` if the frame's last block was reached during this decode.
892 pub frame_finished: bool,
893 /// Cross-block carry-over state for resuming the next extent. Feed it back
894 /// (with the matching `window_prime`) via the `resume` argument of a
895 /// later [`FrameDecoder::decode_blocks_partial`] to continue from
896 /// [`ResumeState::block_index`] without re-decompressing the prefix.
897 ///
898 /// `None` in two cases: emission was not requested (`emit_resume = false`),
899 /// OR this decode reached the frame's last block ([`frame_finished`] is
900 /// `true`) — there is no following block to resume from, so no snapshot is
901 /// emitted even with `emit_resume = true`. Callers walking a frame
902 /// incrementally should therefore stop when `frame_finished` is set rather
903 /// than treat a `None` here as "emission disabled".
904 ///
905 /// [`frame_finished`]: Self::frame_finished
906 pub resume_state: Option<ResumeState>,
907}
908
909impl FrameDecoderState {
910 /// Window size to actually reserve for this frame's decode buffer.
911 /// A declared content size caps the useful window: matches can never
912 /// reference further back than the bytes that will ever exist, so an
913 /// encoder-declared window above the FCS (e.g. a level-preset window
914 /// on a smaller input) must not inflate the reservation. Every
915 /// `reserve_buffer` site routes through this so the cap is uniform
916 /// across `decode_all_impl`, `decode_blocks`, and the partial path.
917 fn useful_window_size(&self) -> usize {
918 let window_size = self.frame_header.window_size().unwrap_or(0);
919 if self.frame_header.fcs_declared() {
920 window_size.min(self.frame_header.frame_content_size()) as usize
921 } else {
922 window_size as usize
923 }
924 }
925
926 /// The most a frame decoding through the buffer holds, which its growth
927 /// stops at. A single-segment frame's buffer holds its whole content,
928 /// which is its window. A multi-segment frame's ring holds the
929 /// content-capped window plus room for the next block, since each
930 /// compressed block reserves a whole block before it decodes: without it
931 /// the first block past a full window grew the ring and copied the window
932 /// across, and a limit at the content left no block of room once the
933 /// window filled. Upstream sizes its stream buffer as window + block too
934 /// (`ZSTD_decodingBufferSize_min`); it can cap at the content because its
935 /// buffer is not a ring.
936 ///
937 /// A declared content size does NOT cap this. A frame can declare less than
938 /// its blocks go on to produce, and that is caught by the check against the
939 /// declaration once the bytes exist; a limit that stopped the ring short of
940 /// them would instead have the write run out of buffer, which the ring
941 /// asserts on rather than reports. Only the up-front reservation takes the
942 /// declaration ([`Self::decoding_buffer_size`]).
943 fn decoding_buffer_limit(&self) -> usize {
944 let useful_window = self.useful_window_size();
945 if self.frame_header.descriptor.single_segment_flag() {
946 return useful_window;
947 }
948 let window_size = self.frame_header.window_size().unwrap_or(0) as usize;
949 // No overflow: the window was checked against
950 // `MAXIMUM_ALLOWED_WINDOW_SIZE` when the header was taken.
951 useful_window + window_size.min(crate::common::MAX_BLOCK_SIZE as usize)
952 }
953
954 /// What to reserve up front: the limit, except for a multi-segment frame
955 /// whose declared content fits its window, which reserves just its
956 /// content. Only compressed blocks need the block of room past it, and
957 /// they reserve it themselves; the limit then caps that growth at one
958 /// block. Such frames are rare (encoders mark a frame that fits its window
959 /// single-segment), and a small Raw or RLE one should not pay a block.
960 ///
961 /// A frame that declares its size never reserves past the declaration: the
962 /// block of room is there for what a block still has to produce, and an
963 /// honest frame produces exactly what it promised. A 1 MiB window declaring
964 /// one byte more reserved a whole block of room for that byte. A frame that
965 /// goes on to exceed its declaration grows into the limit and is then caught
966 /// by the check against it.
967 fn decoding_buffer_size(&self) -> usize {
968 let window_size = self.frame_header.window_size().unwrap_or(0);
969 if !self.frame_header.fcs_declared() {
970 return self.decoding_buffer_limit();
971 }
972 let declared = self.frame_header.frame_content_size();
973 if declared <= window_size {
974 return self.useful_window_size();
975 }
976 self.decoding_buffer_limit()
977 .min(usize::try_from(declared).unwrap_or(usize::MAX))
978 }
979
980 /// Reserve this frame's decode buffer ([`Self::decoding_buffer_size`])
981 /// and cap its later growth ([`Self::decoding_buffer_limit`]).
982 fn reserve_decoding_buffer(&mut self) {
983 let target = self.decoding_buffer_size();
984 let growth_limit = self.decoding_buffer_limit();
985 // What the frame promised to produce, so the per-block reservation can
986 // ask for the smaller of a block and what is left of that promise.
987 let declared = self
988 .frame_header
989 .fcs_declared()
990 .then(|| self.frame_header.frame_content_size());
991 self.decoder_scratch.set_declared_content(declared);
992 self.decoder_scratch.reserve_buffer(target, growth_limit);
993 }
994
995 /// Construct a new frame decoder state, reading the frame header
996 /// from `source`. When `magicless` is `true`, the 4-byte magic
997 /// number prefix is NOT consumed (upstream zstd `ZSTD_f_zstd1_magicless`).
998 /// Crate-internal — reached only via `FrameDecoder::init` /
999 /// `FrameDecoder::init_with_dict_handle`. The decode buffer is
1000 /// allocated lazily on BOTH backends (`new_ring` and `new_flat`):
1001 /// direct-eligible frames pay zero buffer allocation, and the
1002 /// non-direct fallback reserves `window_size` once in
1003 /// `decode_all_impl` / `decode_blocks` via `reserve_buffer` before
1004 /// any block write.
1005 #[inline]
1006 pub(crate) fn new_with_format(
1007 source: impl Read,
1008 magicless: bool,
1009 ) -> Result<FrameDecoderState, FrameDecoderError> {
1010 let (frame, header_size) = frame::read_frame_header_with_format(source, magicless)?;
1011 Self::new_with_parsed_header(frame, header_size)
1012 }
1013
1014 /// Build a fresh state from an already-parsed frame header (the non-parsing
1015 /// tail of [`Self::new_with_format`]). Shared by the `Read` path and the
1016 /// slice-direct path ([`FrameDecoder::reset_from_slice`]).
1017 pub(crate) fn new_with_parsed_header(
1018 frame: frame::FrameHeader,
1019 header_size: u8,
1020 ) -> Result<FrameDecoderState, FrameDecoderError> {
1021 let window_size = frame.window_size()?;
1022
1023 if window_size > MAXIMUM_ALLOWED_WINDOW_SIZE {
1024 return Err(FrameDecoderError::WindowSizeTooBig {
1025 requested: window_size,
1026 });
1027 }
1028
1029 let decoder_scratch = if frame.descriptor.single_segment_flag() {
1030 DecoderScratchKind::new_flat(window_size as usize)
1031 } else {
1032 DecoderScratchKind::new_ring(window_size as usize)
1033 };
1034 Ok(FrameDecoderState {
1035 frame_header: frame,
1036 frame_finished: false,
1037 block_counter: 0,
1038 decoder_scratch,
1039 bytes_read_counter: u64::from(header_size),
1040 check_sum: None,
1041 using_dict: None,
1042 active_dict: None,
1043 })
1044 }
1045
1046 /// Reset this state for a new frame read from `source`, reusing
1047 /// existing allocations. When `magicless` is `true`, the frame
1048 /// header is read WITHOUT expecting a magic-number prefix
1049 /// (upstream zstd `ZSTD_f_zstd1_magicless`). Crate-internal — reached
1050 /// only via `FrameDecoder::reset`.
1051 ///
1052 /// `DecodeBuffer::reset` no longer reserves window_size for either
1053 /// backend — capacity decisions live one layer up. Both backends are
1054 /// lazy: direct-eligible frames pay zero backing-buffer allocation
1055 /// here (they write through `UserSliceBackend`), and the non-direct
1056 /// path is pre-reserved by `decode_all_impl` / `decode_blocks` via
1057 /// `DecoderScratchKind::reserve_buffer(window_size)` before any block
1058 /// write. A reused scratch whose new frame fits within prior capacity
1059 /// reuses it; a larger one grows on that same `reserve_buffer` call.
1060 #[inline]
1061 pub(crate) fn reset_with_format(
1062 &mut self,
1063 source: impl Read,
1064 magicless: bool,
1065 ) -> Result<(), FrameDecoderError> {
1066 let (frame_header, header_size) = frame::read_frame_header_with_format(source, magicless)?;
1067 self.reset_with_parsed_header(frame_header, header_size)
1068 }
1069
1070 /// Apply an already-parsed frame header to this state (the non-parsing tail
1071 /// of [`Self::reset_with_format`]). Shared by the `Read` path and the slice-direct
1072 /// path ([`FrameDecoder::reset_from_slice`]).
1073 #[inline]
1074 pub(crate) fn reset_with_parsed_header(
1075 &mut self,
1076 frame_header: frame::FrameHeader,
1077 header_size: u8,
1078 ) -> Result<(), FrameDecoderError> {
1079 let window_size = frame_header.window_size()?;
1080
1081 if window_size > MAXIMUM_ALLOWED_WINDOW_SIZE {
1082 return Err(FrameDecoderError::WindowSizeTooBig {
1083 requested: window_size,
1084 });
1085 }
1086
1087 self.decoder_scratch
1088 .reset(&frame_header, window_size as usize);
1089 self.frame_header = frame_header;
1090 self.frame_finished = false;
1091 self.block_counter = 0;
1092 self.bytes_read_counter = u64::from(header_size);
1093 self.check_sum = None;
1094 self.using_dict = None;
1095 // `active_dict` is intentionally NOT cleared here: it is only ever READ
1096 // while a scratch table source is `Dict`, which `init_from_dict` arms
1097 // on a dict frame and which a no-dict frame leaves `Local` (so a stale
1098 // held handle is never read). Keeping it lets the per-apply `ptr::eq`
1099 // reuse-check below skip the clone when the SAME dictionary is
1100 // re-applied frame-over-frame (the CoordiNode per-label-dict hot path)
1101 // — zero refcount churn on reuse, one clone only on a genuine swap.
1102 Ok(())
1103 }
1104
1105 /// Hold the dictionary handle for this frame's whole decode so the block
1106 /// loop can borrow `&Dictionary` at every `Dict`-sourced read. Clones the
1107 /// handle ONLY when it is a different dictionary than the one already held
1108 /// (`ptr::eq` on the `Arc`'s pointee) — so re-applying the SAME dictionary
1109 /// frame-over-frame (the reuse hot path) costs zero refcount churn.
1110 fn set_active_dict(&mut self, dict: &DictionaryHandle) {
1111 if self
1112 .active_dict
1113 .as_ref()
1114 .is_none_or(|held| !core::ptr::eq(held.as_dict(), dict.as_dict()))
1115 {
1116 self.active_dict = Some(dict.clone());
1117 }
1118 }
1119}
1120
1121impl Default for FrameDecoder {
1122 fn default() -> Self {
1123 Self::new()
1124 }
1125}
1126
1127impl FrameDecoder {
1128 /// This will create a new decoder without allocating anything yet.
1129 /// init()/reset() will allocate all needed buffers if it is the first time this decoder is used
1130 /// else they just reset these buffers with not further allocations
1131 pub fn new() -> FrameDecoder {
1132 FrameDecoder {
1133 state: None,
1134 #[cfg(test)]
1135 direct_frames: 0,
1136 owned_dicts: BTreeMap::new(),
1137 #[cfg(target_has_atomic = "ptr")]
1138 shared_dicts: BTreeMap::new(),
1139 #[cfg(not(target_has_atomic = "ptr"))]
1140 shared_dicts: (),
1141 magicless: false,
1142 content_checksum: ContentChecksum::EmitOnly,
1143 #[cfg(feature = "lsm")]
1144 expect_dict_id: None,
1145 #[cfg(feature = "lsm")]
1146 expect_window_descriptor: None,
1147 #[cfg(all(feature = "lsm", feature = "hash"))]
1148 per_block_checksums_enabled: false,
1149 #[cfg(all(feature = "lsm", feature = "hash"))]
1150 computed_block_checksums: alloc::vec::Vec::new(),
1151 kernel: crate::cpu_kernel::detect_cpu_kernel(),
1152 }
1153 }
1154
1155 /// Decode with a named CPU tier instead of the one this machine selected.
1156 ///
1157 /// Which tier runs is otherwise a property of the host, so a test on any
1158 /// one machine covers exactly one of them. The tiers are separate
1159 /// monomorphs with their own gates and their own argument plumbing, and
1160 /// a divergence between them is precisely what no single-host run can see.
1161 ///
1162 /// The caller is responsible for naming a tier the CPU can actually
1163 /// execute: the monoliths carry `target_feature`, and asking for one the
1164 /// machine lacks is undefined behaviour rather than an error.
1165 #[cfg(test)]
1166 // Its consumer is the per-tier agreement test, and the tiers worth
1167 // disagreeing are the x86 ones, so on other architectures nothing calls it.
1168 #[allow(dead_code)]
1169 pub(crate) fn decode_with_kernel_for_tests(&mut self, kernel: crate::cpu_kernel::CpuKernelTag) {
1170 self.kernel = kernel;
1171 }
1172
1173 /// Heap bytes currently held by the decoder's lazily-grown workspace:
1174 /// the decode-window buffer plus the per-block literal/content buffers
1175 /// and the entropy tables. Returns 0 before the first frame is initialised
1176 /// (no workspace allocated yet). The window allocation dominates and grows
1177 /// with the frame's window size; this is the value to track for decode-time
1178 /// memory pressure, mirroring the workspace term of upstream
1179 /// `ZSTD_sizeof_DCtx`. Shared dictionaries (ref-counted handles) are not
1180 /// counted, matching upstream excluding `refDDict` memory.
1181 pub fn workspace_size(&self) -> usize {
1182 self.state
1183 .as_ref()
1184 .map_or(0, |s| s.decoder_scratch.workspace_bytes())
1185 }
1186
1187 /// Select how the frame's optional content checksum is handled
1188 /// (compute, expose, verify, or skip). See [`ContentChecksum`].
1189 /// Default [`ContentChecksum::EmitOnly`]. Takes effect on the next
1190 /// decode; safe to call between frames on a reused decoder.
1191 pub fn set_content_checksum(&mut self, mode: ContentChecksum) {
1192 self.content_checksum = mode;
1193 }
1194
1195 /// Opt in to per-block XXH64 verification during decode.
1196 /// Default off; zero cost when disabled. Each block's decompressed
1197 /// bytes are XXH64-hashed (low 32 bits) and appended to
1198 /// [`Self::computed_block_checksums`] as the decode progresses.
1199 /// Callers compare the captured digests against externally-stored
1200 /// expected values (e.g. from a per-block sidecar in the
1201 /// containing application protocol).
1202 ///
1203 /// Behind `all(feature = "lsm", feature = "hash")` — the XXH64
1204 /// primitive lives behind the `hash` feature, so this method
1205 /// only compiles when both are enabled.
1206 #[cfg(all(feature = "lsm", feature = "hash"))]
1207 pub fn enable_per_block_checksums(&mut self) {
1208 self.per_block_checksums_enabled = true;
1209 }
1210
1211 /// Per-block XXH64 (low 32 bits) digests captured during the
1212 /// current frame's decode. Empty unless
1213 /// [`Self::enable_per_block_checksums`] was called before
1214 /// [`Self::decode_all`] / [`Self::reset`].
1215 ///
1216 /// Reset at the start of every new frame.
1217 ///
1218 /// Behind `all(feature = "lsm", feature = "hash")`.
1219 #[cfg(all(feature = "lsm", feature = "hash"))]
1220 pub fn computed_block_checksums(&self) -> &[u32] {
1221 &self.computed_block_checksums
1222 }
1223
1224 /// Pin the expected `Dictionary_ID` for the next frame.
1225 ///
1226 /// When `expected` is set, [`Self::init`] / [`Self::reset`]
1227 /// validate it against the parsed frame header BEFORE any
1228 /// block decode work runs. A mismatch returns
1229 /// [`crate::decoding::errors::FrameDecoderError::UnexpectedDictId`]
1230 /// before any block decode and before any output is produced.
1231 /// Scratch buffer allocation / reservation for the decode
1232 /// pipeline happens during frame-header parsing, which is
1233 /// already complete when this validation fires — the cost of
1234 /// scratch sizing is paid even on a mismatched header. The
1235 /// guarantee is "no block decode, no XXH64 init, no partial
1236 /// output", not "zero allocation".
1237 ///
1238 /// `Some(0)` is treated as "no dictionary expected": a frame
1239 /// whose header omits the optional `Dictionary_ID` field
1240 /// (flag value 0) passes the check; a frame that carries an
1241 /// explicit non-zero id fails.
1242 ///
1243 /// `None` (default) disables the check.
1244 ///
1245 /// Primary use case: post-AEAD-decrypt sanity check in
1246 /// wire-format consumers (e.g. lsm-tree's encrypted block
1247 /// format pins the `dict_id` baked into the AAD against the
1248 /// inner zstd frame's `dict_id` to defeat dict-substitution
1249 /// attacks).
1250 ///
1251 /// NOT a replacement for AEAD authentication. NOT the same
1252 /// semantic as upstream zstd `ZSTD_d_windowLogMax` (which is a
1253 /// ceiling-style limit, separate concern).
1254 #[cfg(feature = "lsm")]
1255 #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
1256 pub fn expect_dict_id(&mut self, expected: Option<u32>) {
1257 self.expect_dict_id = expected;
1258 }
1259
1260 /// Pin the expected raw `Window_Descriptor` byte (RFC 8878
1261 /// §3.1.1.1.2 layout: `(exp << 3) | mantissa`) for the next
1262 /// frame.
1263 ///
1264 /// When `expected` is set, [`Self::init`] / [`Self::reset`]
1265 /// validate it against the parsed frame header BEFORE any
1266 /// block decode work runs. A mismatch returns
1267 /// [`crate::decoding::errors::FrameDecoderError::UnexpectedWindowDescriptor`].
1268 ///
1269 /// Single-segment frames omit the `Window_Descriptor` byte
1270 /// from the wire entirely. Setting an expectation while
1271 /// receiving a single-segment frame fails the check with
1272 /// `found: None` — there is no on-wire byte to match against,
1273 /// which is reported explicitly rather than silently passing.
1274 ///
1275 /// `None` (default) disables the check.
1276 ///
1277 /// Byte-exact equality, NOT a ceiling. Upstream zstd
1278 /// `ZSTD_d_windowLogMax` is a separate ceiling-style limit
1279 /// available through the C FFI surface; this method is for
1280 /// strict equality validation against a pinned expectation
1281 /// (e.g. lsm-tree's wire format pins the window descriptor
1282 /// from the AAD to defeat decompression-bomb-swap attacks).
1283 #[cfg(feature = "lsm")]
1284 #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
1285 pub fn expect_window_descriptor(&mut self, expected: Option<u8>) {
1286 self.expect_window_descriptor = expected;
1287 }
1288
1289 /// Validate the just-parsed frame header against any pinned
1290 /// expectations set via [`Self::expect_dict_id`] /
1291 /// [`Self::expect_window_descriptor`].
1292 ///
1293 /// Returns the typed error variant on mismatch and leaves
1294 /// `self.state` in a re-resettable shape — a subsequent
1295 /// `reset()` will overwrite `frame_header` from the new source
1296 /// without needing intermediate cleanup.
1297 #[cfg(feature = "lsm")]
1298 fn validate_expectations(
1299 &self,
1300 frame_header: &frame::FrameHeader,
1301 ) -> Result<(), FrameDecoderError> {
1302 if let Some(expected) = self.expect_dict_id {
1303 let found = frame_header.dictionary_id();
1304 // `Some(0)` is the "no dictionary expected" sentinel —
1305 // matches a frame whose header omits the optional
1306 // dict_id field (which is reported as `None` by the
1307 // parser). All other values must match exactly.
1308 let matches = match (expected, found) {
1309 (0, None) => true,
1310 (e, Some(f)) => e == f,
1311 _ => false,
1312 };
1313 if !matches {
1314 return Err(FrameDecoderError::UnexpectedDictId {
1315 expected: Some(expected),
1316 found,
1317 });
1318 }
1319 }
1320 if let Some(expected) = self.expect_window_descriptor {
1321 let found = frame_header.window_descriptor();
1322 if found != Some(expected) {
1323 return Err(FrameDecoderError::UnexpectedWindowDescriptor { expected, found });
1324 }
1325 }
1326 Ok(())
1327 }
1328
1329 /// Enable or disable magicless frame format
1330 /// (`ZSTD_f_zstd1_magicless`). When set to `true`, subsequent
1331 /// [`Self::init`] / [`Self::reset`] calls expect the frame header to begin
1332 /// directly with the frame-header descriptor — no 4-byte magic
1333 /// number prefix. Default false. Must match the encoder's
1334 /// magicless setting; the format is unambiguous only when the
1335 /// caller knows it out-of-band.
1336 ///
1337 /// Note: magicless mode also disables skippable-frame detection.
1338 /// The `0x184D2A50..=0x184D2A5F` skippable-frame magic range is
1339 /// only recognised when the 4-byte magic prefix is consumed, so
1340 /// `decode_all` / `init` / `reset` will treat a skippable frame
1341 /// at the head of a magicless stream as a malformed frame header
1342 /// (bad descriptor / window-size error) instead of skipping it.
1343 /// Mixed-format streams that interleave skippable frames must be
1344 /// pre-split by the caller; `set_magicless(true)` is only safe
1345 /// when the entire stream is known to be magicless zstd frames.
1346 pub fn set_magicless(&mut self, magicless: bool) {
1347 self.magicless = magicless;
1348 }
1349
1350 /// Whether frame headers are read without the magic number.
1351 pub(crate) fn is_magicless(&self) -> bool {
1352 self.magicless
1353 }
1354
1355 /// Whether every block of the frame is decoded and only its trailing
1356 /// content checksum is still to be read.
1357 pub(crate) fn awaits_checksum(&self) -> bool {
1358 self.state.as_ref().is_some_and(|state| {
1359 state.frame_finished
1360 && state.frame_header.descriptor.content_checksum_flag()
1361 && state.check_sum.is_none()
1362 })
1363 }
1364
1365 /// How many bytes from the start of `pending` the current frame's next
1366 /// step needs in hand: a block header, a whole block, or the trailing
1367 /// checksum; 0 once the frame wants no more input. Upstream zstd's
1368 /// `ZSTD_nextSrcSizeToDecompress`. A block stating more than the frame's
1369 /// block maximum needs only its header, whose decode then reports it.
1370 pub(crate) fn input_needed(&self, pending: &[u8]) -> usize {
1371 let Some(state) = self.state.as_ref() else {
1372 return 0;
1373 };
1374 if state.frame_finished {
1375 let checksum_due =
1376 state.frame_header.descriptor.content_checksum_flag() && state.check_sum.is_none();
1377 return if checksum_due { 4 } else { 0 };
1378 }
1379 let Some(&[b0, b1, b2]) = pending.first_chunk::<3>() else {
1380 return 3;
1381 };
1382 // RFC 8878 3.1.1.2: Last_Block (bit 0), Block_Type (bits 1-2),
1383 // Block_Size (bits 3-23). A Reserved block (3.1.1.2.2) is invalid
1384 // from its header alone. Block_Size is held to the block maximum for
1385 // every type: for an RLE block it is the repeat count, while its
1386 // content is one byte.
1387 let header = u32::from_le_bytes([b0, b1, b2, 0]);
1388 let block_type = (header >> 1) & 3;
1389 if block_type == 3 {
1390 return 3;
1391 }
1392 let size = (header >> 3) as usize;
1393 // A window wider than the address space cannot bound a block below
1394 // the 128 KiB maximum, so it counts as unbounded here.
1395 let window = state
1396 .frame_header
1397 .window_size()
1398 .map_or(usize::MAX, |w| usize::try_from(w).unwrap_or(usize::MAX));
1399 if size > decoding::block_decoder::block_maximum(window) {
1400 return 3;
1401 }
1402 // The block header is parsed again by the block decoder. Carrying it
1403 // across would cost a stored field per block for three byte loads.
1404 3 + if block_type == 1 { 1 } else { size }
1405 }
1406
1407 /// Start the Raw block whose 3-byte header is `header`, its content to
1408 /// follow in parts through [`Self::raw_block_push`] as the source delivers
1409 /// it, instead of being gathered whole first. Returns the
1410 /// block's size and whether it is the frame's last; `Ok(None)`, with
1411 /// nothing consumed, when `header` is not a Raw block's, or the frame
1412 /// expects no block (its blocks are done and its checksum is next).
1413 /// `reserve_window` is as for [`Self::decode_available`].
1414 pub(crate) fn start_raw_block(
1415 &mut self,
1416 header: &[u8; 3],
1417 reserve_window: bool,
1418 ) -> Result<Option<(u32, bool)>, FrameDecoderError> {
1419 let kernel = self.kernel;
1420 #[cfg(feature = "hash")]
1421 let checksum_mode = self.content_checksum;
1422 let state = self
1423 .state
1424 .as_mut()
1425 .ok_or(FrameDecoderError::NotYetInitialized)?;
1426 // RFC 8878 3.1.1.2.2: Block_Type 0 is Raw.
1427 if state.frame_finished || (header[0] >> 1) & 3 != 0 {
1428 return Ok(None);
1429 }
1430 // The checksum mode is applied before any of the frame's output is
1431 // written, as `decode_available` applies it.
1432 #[cfg(feature = "hash")]
1433 {
1434 let compute_hash = checksum_mode != ContentChecksum::None
1435 && state.frame_header.descriptor.content_checksum_flag();
1436 state.decoder_scratch.set_compute_hash(compute_hash);
1437 }
1438 let block_index = state.block_counter as u32;
1439 let block_frame_offset = state.bytes_read_counter as u32;
1440 let mut block_dec = decoding::block_decoder::with_kernel(kernel);
1441 let (block_header, header_size) = block_dec
1442 .read_block_header(&header[..])
1443 .map_err(|source| block_header_decode_error(source, block_index, block_frame_offset))?;
1444 let window = state
1445 .frame_header
1446 .window_size()
1447 .map_or(usize::MAX, |w| usize::try_from(w).unwrap_or(usize::MAX));
1448 decoding::block_decoder::block_fits_the_maximum(&block_header, window).map_err(
1449 |source| {
1450 block_body_decode_error(
1451 source,
1452 block_index,
1453 block_frame_offset,
1454 &block_header,
1455 header_size,
1456 )
1457 },
1458 )?;
1459 state.bytes_read_counter += u64::from(header_size);
1460 if state.block_counter == 0 && (reserve_window || state.frame_header.fcs_declared()) {
1461 state.reserve_decoding_buffer();
1462 }
1463 Ok(Some((
1464 block_header.decompressed_size,
1465 block_header.last_block,
1466 )))
1467 }
1468
1469 /// Append `content`, the next part of the Raw block in progress, to the
1470 /// decode buffer.
1471 pub(crate) fn raw_block_push(&mut self, content: &[u8]) {
1472 let kernel = self.kernel;
1473 let state = self
1474 .state
1475 .as_mut()
1476 .expect("a Raw block is started on an initialised frame");
1477 state.decoder_scratch.buffer_push(content, kernel);
1478 }
1479
1480 /// Whether [`Self::enable_per_block_checksums`] asked for block digests.
1481 #[cfg(all(feature = "lsm", feature = "hash"))]
1482 pub(crate) fn per_block_checksums_enabled(&self) -> bool {
1483 self.per_block_checksums_enabled
1484 }
1485
1486 /// Record the digest of a block decoded outside this decoder's own block
1487 /// loops, in block order.
1488 #[cfg(all(feature = "lsm", feature = "hash"))]
1489 pub(crate) fn record_block_checksum(&mut self, digest: u32) {
1490 self.computed_block_checksums.push(digest);
1491 }
1492
1493 /// The error for a source that ended inside the Raw block of `size` bytes
1494 /// in progress: a body read cut short, as the block decoder reports it.
1495 pub(crate) fn raw_block_cut_short(&self, size: u32, last: bool) -> FrameDecoderError {
1496 let state = self
1497 .state
1498 .as_ref()
1499 .expect("a Raw block is started on an initialised frame");
1500 let header = crate::blocks::block::BlockHeader {
1501 last_block: last,
1502 block_type: crate::blocks::block::BlockType::Raw,
1503 decompressed_size: size,
1504 content_size: size,
1505 };
1506 block_body_decode_error(
1507 DecodeBlockContentError::ReadError {
1508 step: crate::blocks::block::BlockType::Raw,
1509 source: Error::from(crate::io::ErrorKind::UnexpectedEof),
1510 },
1511 state.block_counter as u32,
1512 // The header was counted when the block started.
1513 (state.bytes_read_counter - 3) as u32,
1514 &header,
1515 3,
1516 )
1517 }
1518
1519 /// Close the Raw block of `size` bytes whose content is all appended.
1520 pub(crate) fn finish_raw_block(&mut self, size: u32, last: bool) {
1521 let state = self
1522 .state
1523 .as_mut()
1524 .expect("a Raw block is started on an initialised frame");
1525 state.bytes_read_counter += u64::from(size);
1526 state.block_counter += 1;
1527 if last {
1528 state.frame_finished = true;
1529 }
1530 }
1531
1532 #[cfg(target_has_atomic = "ptr")]
1533 fn shared_dict_exists(&self, dict_id: u32) -> bool {
1534 self.shared_dicts.contains_key(&dict_id)
1535 }
1536
1537 #[cfg(not(target_has_atomic = "ptr"))]
1538 fn shared_dict_exists(&self, _dict_id: u32) -> bool {
1539 false
1540 }
1541
1542 fn validate_registered_dictionary(dict: &Dictionary) -> Result<(), FrameDecoderError> {
1543 use crate::decoding::errors::DictionaryDecodeError as dict_err;
1544
1545 // Registration keys the dictionary by its ID, so a zero one has no
1546 // slot to occupy and no frame could ever select it.
1547 if dict.id == 0 {
1548 return Err(FrameDecoderError::from(dict_err::ZeroDictionaryId));
1549 }
1550 Self::validate_dictionary_content(dict)
1551 }
1552
1553 /// Checks a dictionary can be used at all, whatever route it arrived by.
1554 ///
1555 /// Separate from [`Self::validate_registered_dictionary`] because a
1556 /// dictionary supplied explicitly needs no ID: a raw-content dictionary
1557 /// has no header to carry one, and the frames built with it record none.
1558 fn validate_dictionary_content(dict: &Dictionary) -> Result<(), FrameDecoderError> {
1559 use crate::decoding::errors::DictionaryDecodeError as dict_err;
1560
1561 if let Some(index) = dict.offset_hist.iter().position(|&rep| rep == 0) {
1562 return Err(FrameDecoderError::from(
1563 dict_err::ZeroRepeatOffsetInDictionary { index: index as u8 },
1564 ));
1565 }
1566 Ok(())
1567 }
1568
1569 /// init() will allocate all needed buffers if it is the first time this decoder is used
1570 /// else they just reset these buffers with not further allocations
1571 ///
1572 /// Note that all bytes currently in the decodebuffer from any previous frame will be lost. Collect them with collect()/collect_to_writer()
1573 ///
1574 /// equivalent to reset()
1575 #[inline]
1576 pub fn init(&mut self, source: impl Read) -> Result<(), FrameDecoderError> {
1577 self.reset(source)
1578 }
1579
1580 /// Initialize the decoder for a new frame using a pre-parsed dictionary handle.
1581 ///
1582 /// If the frame header has a dictionary ID, this validates it against
1583 /// `dict.id()` and returns [`FrameDecoderError::DictIdMismatch`] on mismatch.
1584 ///
1585 /// If the header omits the optional dictionary ID, this still applies the
1586 /// provided dictionary handle.
1587 ///
1588 /// # Warning
1589 ///
1590 /// This method always applies `dict` unless the frame header contains a
1591 /// non-matching dictionary ID. Callers must only use this API when they
1592 /// already know the frame was encoded with the provided dictionary, even if
1593 /// the frame header omits the dictionary ID or encodes an explicit
1594 /// dictionary ID of `0`.
1595 ///
1596 /// Passing a dictionary for a frame that was not encoded with it can
1597 /// silently corrupt the decoded output.
1598 pub fn init_with_dict_handle(
1599 &mut self,
1600 source: impl Read,
1601 dict: &DictionaryHandle,
1602 ) -> Result<(), FrameDecoderError> {
1603 self.reset_with_dict_handle(source, dict)
1604 }
1605
1606 /// reset() will allocate all needed buffers if it is the first time this decoder is used
1607 /// else they just reset these buffers with not further allocations
1608 ///
1609 /// Note that all bytes currently in the decodebuffer from any previous frame will be lost. Collect them with collect()/collect_to_writer()
1610 ///
1611 /// equivalent to init()
1612 #[inline]
1613 pub fn reset(&mut self, source: impl Read) -> Result<(), FrameDecoderError> {
1614 use FrameDecoderError as err;
1615 // Fresh frame → start with an empty per-block checksum vec so
1616 // the values for the next frame don't carry over from the
1617 // previous one.
1618 #[cfg(all(feature = "lsm", feature = "hash"))]
1619 self.computed_block_checksums.clear();
1620 let magicless = self.magicless;
1621 let dict_id = match &mut self.state {
1622 Some(s) => {
1623 s.reset_with_format(source, magicless)?;
1624 s.frame_header.dictionary_id()
1625 }
1626 None => {
1627 self.state = Some(FrameDecoderState::new_with_format(source, magicless)?);
1628 self.state
1629 .as_ref()
1630 .and_then(|state| state.frame_header.dictionary_id())
1631 }
1632 };
1633 // Validate any pinned expectations BEFORE block decode work
1634 // runs. Catches dict_id substitution / window-descriptor
1635 // tampering on inputs already authenticated by an outer
1636 // layer (e.g. AEAD). Returning here leaves `self.state` in
1637 // a re-resettable shape — next `reset()` re-parses the
1638 // frame header without intermediate cleanup.
1639 #[cfg(feature = "lsm")]
1640 if let Some(state) = self.state.as_ref() {
1641 self.validate_expectations(&state.frame_header)?;
1642 }
1643 if let Some(dict_id) = dict_id {
1644 let state = self.state.as_mut().expect("state initialized");
1645 let owned_dicts = &self.owned_dicts;
1646 #[cfg(target_has_atomic = "ptr")]
1647 let shared_dicts = &self.shared_dicts;
1648 let dict = owned_dicts
1649 .get(&dict_id)
1650 .or_else(|| {
1651 #[cfg(target_has_atomic = "ptr")]
1652 {
1653 shared_dicts.get(&dict_id)
1654 }
1655 #[cfg(not(target_has_atomic = "ptr"))]
1656 {
1657 None
1658 }
1659 })
1660 .ok_or(err::DictNotProvided { dict_id })?;
1661 state.decoder_scratch.init_from_dict(dict);
1662 state.set_active_dict(dict);
1663 state.using_dict = Some(dict_id);
1664 }
1665 Ok(())
1666 }
1667
1668 /// Slice-direct equivalent of [`reset`](Self::reset) for the in-memory
1669 /// decode path: parses the frame header straight out of `*input` via
1670 /// [`frame::read_frame_header_from_slice`] (no `Read`-trait `read_exact`
1671 /// per field) and advances `*input` past it, then applies it through the
1672 /// shared parsed-header path. Behaviour — including skippable-frame and
1673 /// truncation errors, dictionary-id resolution, and pinned-expectation
1674 /// validation — is identical to `reset`; only the header read avoids the
1675 /// `io::impls` dispatch.
1676 pub(crate) fn reset_from_slice(&mut self, input: &mut &[u8]) -> Result<(), FrameDecoderError> {
1677 use FrameDecoderError as err;
1678 #[cfg(all(feature = "lsm", feature = "hash"))]
1679 self.computed_block_checksums.clear();
1680 let magicless = self.magicless;
1681 let (frame_header, header_size) = frame::read_frame_header_from_slice(input, magicless)?;
1682 let dict_id = match &mut self.state {
1683 Some(s) => {
1684 s.reset_with_parsed_header(frame_header, header_size)?;
1685 s.frame_header.dictionary_id()
1686 }
1687 None => {
1688 self.state = Some(FrameDecoderState::new_with_parsed_header(
1689 frame_header,
1690 header_size,
1691 )?);
1692 self.state
1693 .as_ref()
1694 .and_then(|state| state.frame_header.dictionary_id())
1695 }
1696 };
1697 #[cfg(feature = "lsm")]
1698 if let Some(state) = self.state.as_ref() {
1699 self.validate_expectations(&state.frame_header)?;
1700 }
1701 if let Some(dict_id) = dict_id {
1702 let state = self.state.as_mut().expect("state initialized");
1703 let owned_dicts = &self.owned_dicts;
1704 #[cfg(target_has_atomic = "ptr")]
1705 let shared_dicts = &self.shared_dicts;
1706 let dict = owned_dicts
1707 .get(&dict_id)
1708 .or_else(|| {
1709 #[cfg(target_has_atomic = "ptr")]
1710 {
1711 shared_dicts.get(&dict_id)
1712 }
1713 #[cfg(not(target_has_atomic = "ptr"))]
1714 {
1715 None
1716 }
1717 })
1718 .ok_or(err::DictNotProvided { dict_id })?;
1719 state.decoder_scratch.init_from_dict(dict);
1720 state.set_active_dict(dict);
1721 state.using_dict = Some(dict_id);
1722 }
1723 Ok(())
1724 }
1725
1726 /// Reset this decoder for a new frame using a pre-parsed dictionary handle.
1727 ///
1728 /// If the frame header has a dictionary ID, this validates it against
1729 /// `dict.id()` and returns [`FrameDecoderError::DictIdMismatch`] on mismatch.
1730 ///
1731 /// If the header omits the optional dictionary ID, this still applies the
1732 /// provided dictionary handle.
1733 ///
1734 /// # Warning
1735 ///
1736 /// This method always applies `dict` unless the frame header contains a
1737 /// non-matching dictionary ID. Callers must only use this API when they
1738 /// already know the frame was encoded with the provided dictionary, even if
1739 /// the frame header omits the dictionary ID or encodes an explicit
1740 /// dictionary ID of `0`.
1741 ///
1742 /// Passing a dictionary for a frame that was not encoded with it can
1743 /// silently corrupt the decoded output.
1744 pub fn reset_with_dict_handle(
1745 &mut self,
1746 source: impl Read,
1747 dict: &DictionaryHandle,
1748 ) -> Result<(), FrameDecoderError> {
1749 self.reset_frame_for_dict(source, dict)?;
1750 self.state
1751 .as_mut()
1752 .expect("state populated by reset_frame_for_dict")
1753 .set_active_dict(dict);
1754 Ok(())
1755 }
1756
1757 /// [`reset_with_dict_handle`](Self::reset_with_dict_handle) with the
1758 /// dictionary the decode state already holds, for the frames that follow
1759 /// a forced-dictionary frame in one stream. The handle is moved out and
1760 /// back rather than passed in, so no reference count is touched.
1761 pub(crate) fn reset_with_active_dict(
1762 &mut self,
1763 source: impl Read,
1764 ) -> Result<(), FrameDecoderError> {
1765 let dict = self
1766 .state
1767 .as_mut()
1768 .and_then(|state| state.active_dict.take())
1769 .expect("a forced-dictionary stream's decoder holds its dictionary");
1770 let reset = self.reset_frame_for_dict(source, &dict);
1771 // Back in place whatever the outcome, so a failed header leaves the
1772 // decoder holding its dictionary as before.
1773 self.state
1774 .as_mut()
1775 .expect("the state the dictionary was taken from")
1776 .active_dict = Some(dict);
1777 reset
1778 }
1779
1780 /// Everything [`reset_with_dict_handle`](Self::reset_with_dict_handle)
1781 /// does except storing the handle: parse the header, check the ID, and
1782 /// point the entropy tables at `dict`.
1783 fn reset_frame_for_dict(
1784 &mut self,
1785 source: impl Read,
1786 dict: &DictionaryHandle,
1787 ) -> Result<(), FrameDecoderError> {
1788 use FrameDecoderError as err;
1789 // Fresh frame → drop the previous frame's per-block checksum
1790 // digests so the next decode starts with an empty vec.
1791 // Mirrors the same clear in `reset()`; reset_with_dict_handle
1792 // is a parallel entry point so it needs its own call.
1793 #[cfg(all(feature = "lsm", feature = "hash"))]
1794 self.computed_block_checksums.clear();
1795 Self::validate_dictionary_content(dict.as_dict())?;
1796 let magicless = self.magicless;
1797 // Scope the &mut borrow of `self.state` to the header parse
1798 // alone, so the subsequent `validate_expectations(&self, ...)`
1799 // call below can take a fresh shared borrow of self without
1800 // tripping the borrow checker.
1801 match &mut self.state {
1802 Some(s) => s.reset_with_format(source, magicless)?,
1803 None => {
1804 self.state = Some(FrameDecoderState::new_with_format(source, magicless)?);
1805 }
1806 }
1807 // Single source of truth: route through the same
1808 // `validate_expectations` used by `reset()`. Routing through
1809 // the helper keeps the two code paths from drifting (e.g.,
1810 // if expect-semantics or error wiring changes later).
1811 #[cfg(feature = "lsm")]
1812 {
1813 let header = &self
1814 .state
1815 .as_ref()
1816 .expect("state populated by reset_with_format/new_with_format")
1817 .frame_header;
1818 self.validate_expectations(header)?;
1819 }
1820 let state = self
1821 .state
1822 .as_mut()
1823 .expect("state populated by reset_with_format/new_with_format");
1824 if let Some(dict_id) = state.frame_header.dictionary_id()
1825 && dict_id != dict.id()
1826 {
1827 return Err(err::DictIdMismatch {
1828 expected: dict_id,
1829 provided: dict.id(),
1830 });
1831 }
1832 state.decoder_scratch.init_from_dict(dict);
1833 state.using_dict = Some(dict.id());
1834 Ok(())
1835 }
1836
1837 /// Slice-direct equivalent of [`reset_with_dict_handle`](Self::reset_with_dict_handle)
1838 /// for the in-memory decode path: parses the frame header straight out of
1839 /// `*input` via [`frame::read_frame_header_from_slice`] (no `Read`-trait
1840 /// `read_exact` per field) and applies it through the shared parsed-header
1841 /// path, then attaches `dict`. Behaviour — dictionary-id mismatch, pinned
1842 /// expectations, scratch init — is identical to `reset_with_dict_handle`;
1843 /// only the header read avoids the `io::impls` dispatch.
1844 pub(crate) fn reset_from_slice_with_dict_handle(
1845 &mut self,
1846 input: &mut &[u8],
1847 dict: &DictionaryHandle,
1848 ) -> Result<(), FrameDecoderError> {
1849 use FrameDecoderError as err;
1850 #[cfg(all(feature = "lsm", feature = "hash"))]
1851 self.computed_block_checksums.clear();
1852 Self::validate_dictionary_content(dict.as_dict())?;
1853 let magicless = self.magicless;
1854 let (frame_header, header_size) = frame::read_frame_header_from_slice(input, magicless)?;
1855 match &mut self.state {
1856 Some(s) => s.reset_with_parsed_header(frame_header, header_size)?,
1857 None => {
1858 self.state = Some(FrameDecoderState::new_with_parsed_header(
1859 frame_header,
1860 header_size,
1861 )?);
1862 }
1863 }
1864 #[cfg(feature = "lsm")]
1865 {
1866 let header = &self
1867 .state
1868 .as_ref()
1869 .expect("state populated by reset_with_parsed_header/new_with_parsed_header")
1870 .frame_header;
1871 self.validate_expectations(header)?;
1872 }
1873 let state = self
1874 .state
1875 .as_mut()
1876 .expect("state populated by reset_with_parsed_header/new_with_parsed_header");
1877 if let Some(dict_id) = state.frame_header.dictionary_id()
1878 && dict_id != dict.id()
1879 {
1880 return Err(err::DictIdMismatch {
1881 expected: dict_id,
1882 provided: dict.id(),
1883 });
1884 }
1885 state.decoder_scratch.init_from_dict(dict);
1886 state.set_active_dict(dict);
1887 state.using_dict = Some(dict.id());
1888 Ok(())
1889 }
1890
1891 /// Add a dictionary that can be selected dynamically by frame dictionary ID.
1892 ///
1893 /// Returns [`FrameDecoderError::DictAlreadyRegistered`] if the ID is already
1894 /// registered (either as owned or shared).
1895 pub fn add_dict(&mut self, dict: Dictionary) -> Result<(), FrameDecoderError> {
1896 Self::validate_registered_dictionary(&dict)?;
1897 let dict_id = dict.id;
1898 if self.owned_dicts.contains_key(&dict_id) || self.shared_dict_exists(dict_id) {
1899 return Err(FrameDecoderError::DictAlreadyRegistered { dict_id });
1900 }
1901 self.owned_dicts
1902 .insert(dict_id, DictionaryHandle::from_dictionary(dict));
1903 Ok(())
1904 }
1905
1906 /// Parse and add a serialized dictionary blob.
1907 pub fn add_dict_from_bytes(&mut self, raw_dictionary: &[u8]) -> Result<(), FrameDecoderError> {
1908 let dict = Dictionary::decode_dict(raw_dictionary)?;
1909 self.add_dict(dict)
1910 }
1911
1912 /// Add a pre-parsed dictionary handle for reuse across decoders.
1913 ///
1914 /// This API is available on targets with pointer-width atomics
1915 /// (`target_has_atomic = "ptr"`).
1916 ///
1917 /// Returns [`FrameDecoderError::DictAlreadyRegistered`] if the ID is already
1918 /// registered (either as owned or shared).
1919 #[cfg(target_has_atomic = "ptr")]
1920 pub fn add_dict_handle(&mut self, dict: DictionaryHandle) -> Result<(), FrameDecoderError> {
1921 Self::validate_registered_dictionary(dict.as_dict())?;
1922 let dict_id = dict.id();
1923 if self.owned_dicts.contains_key(&dict_id) || self.shared_dicts.contains_key(&dict_id) {
1924 return Err(FrameDecoderError::DictAlreadyRegistered { dict_id });
1925 }
1926 self.shared_dicts.insert(dict_id, dict);
1927 Ok(())
1928 }
1929
1930 pub fn force_dict(&mut self, dict_id: u32) -> Result<(), FrameDecoderError> {
1931 use FrameDecoderError as err;
1932 let state = self.state.as_mut().ok_or(err::NotYetInitialized)?;
1933 let owned_dicts = &self.owned_dicts;
1934 #[cfg(target_has_atomic = "ptr")]
1935 let shared_dicts = &self.shared_dicts;
1936
1937 let dict = owned_dicts
1938 .get(&dict_id)
1939 .or_else(|| {
1940 #[cfg(target_has_atomic = "ptr")]
1941 {
1942 shared_dicts.get(&dict_id)
1943 }
1944 #[cfg(not(target_has_atomic = "ptr"))]
1945 {
1946 None
1947 }
1948 })
1949 .ok_or(err::DictNotProvided { dict_id })?;
1950 state.decoder_scratch.init_from_dict(dict);
1951 state.set_active_dict(dict);
1952 state.using_dict = Some(dict_id);
1953
1954 Ok(())
1955 }
1956
1957 /// Returns how many bytes the frame contains after decompression
1958 pub fn content_size(&self) -> u64 {
1959 match &self.state {
1960 None => 0,
1961 Some(s) => s.frame_header.frame_content_size(),
1962 }
1963 }
1964
1965 /// 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
1966 pub fn get_checksum_from_data(&self) -> Option<u32> {
1967 let state = self.state.as_ref()?;
1968
1969 state.check_sum
1970 }
1971
1972 /// Returns the checksum that was calculated while decoding.
1973 /// Only a sensible value after all decoded bytes have been collected/read from the FrameDecoder.
1974 /// Returns `None` when the frame header has `content_checksum_flag = 0`:
1975 /// no hash is computed for such frames (the post-decode XXH64 pass was a
1976 /// 63 % decode-wall hotspot on flag-off frames; skipping it when the
1977 /// frame format declares no trailing digest avoids that wasted work).
1978 #[cfg(feature = "hash")]
1979 pub fn get_calculated_checksum(&self) -> Option<u32> {
1980 let state = self.state.as_ref()?;
1981 // `ContentChecksum::None` skips the XXH64 pass entirely, so there is
1982 // no calculated digest to report.
1983 if self.content_checksum == ContentChecksum::None {
1984 return None;
1985 }
1986 if !state.frame_header.descriptor.content_checksum_flag() {
1987 return None;
1988 }
1989 let cksum_64bit = state.decoder_scratch.hash_finish();
1990 //truncate to lower 32bit because reasons...
1991 Some(cksum_64bit as u32)
1992 }
1993
1994 /// Check that a finished frame produced exactly the `Frame_Content_Size` its
1995 /// header declared (RFC 8878 3.1.1.1.4), returning
1996 /// [`FrameDecoderError::FrameContentSizeMismatch`] otherwise. No-op for a
1997 /// frame that declares no size or has not decoded its last block yet.
1998 ///
1999 /// [`decode_all`](Self::decode_all), [`decode_from_to`](Self::decode_from_to)
2000 /// and the streaming reader call this automatically. Callers driving
2001 /// [`decode_blocks`](Self::decode_blocks) directly invoke it once the
2002 /// frame is finished, as upstream zstd checks at its last block.
2003 ///
2004 /// # Examples
2005 /// ```
2006 /// use structured_zstd::decoding::{BlockDecodingStrategy, FrameDecoder};
2007 /// use structured_zstd::encoding::{compress_to_vec, CompressionLevel};
2008 ///
2009 /// let frame = compress_to_vec(&b"declared and delivered"[..], CompressionLevel::Fastest);
2010 /// let mut source = frame.as_slice();
2011 /// let mut decoder = FrameDecoder::new();
2012 /// decoder.init(&mut source).unwrap();
2013 /// decoder.decode_blocks(&mut source, BlockDecodingStrategy::All).unwrap();
2014 /// assert!(decoder.is_finished());
2015 /// decoder.verify_content_size().unwrap();
2016 /// assert_eq!(decoder.collect().unwrap(), b"declared and delivered");
2017 /// ```
2018 pub fn verify_content_size(&self) -> Result<(), FrameDecoderError> {
2019 let Some(state) = self.state.as_ref() else {
2020 return Ok(());
2021 };
2022 if !state.frame_finished || !state.frame_header.fcs_declared() {
2023 return Ok(());
2024 }
2025 let declared = state.frame_header.frame_content_size();
2026 let produced = state.decoder_scratch.total_output();
2027 if produced != declared {
2028 return Err(FrameDecoderError::FrameContentSizeMismatch { declared, produced });
2029 }
2030 Ok(())
2031 }
2032
2033 /// Compare the frame's stored content checksum against the digest the
2034 /// decoder computed, returning [`FrameDecoderError::ChecksumMismatch`] on
2035 /// disagreement. No-op unless the mode is [`ContentChecksum::Verify`] and
2036 /// the frame carries a trailing checksum.
2037 ///
2038 /// [`decode_all`](Self::decode_all) and the streaming reader call this
2039 /// automatically. Callers driving [`decode_blocks`](Self::decode_blocks)
2040 /// directly invoke it themselves once per frame, after the frame is fully
2041 /// decoded AND fully drained (e.g. via [`collect`](Self::collect)), so both
2042 /// the stored value and the running digest are final.
2043 #[cfg(feature = "hash")]
2044 pub fn verify_content_checksum(&self) -> Result<(), FrameDecoderError> {
2045 if self.content_checksum != ContentChecksum::Verify {
2046 return Ok(());
2047 }
2048 let Some(state) = self.state.as_ref() else {
2049 return Ok(());
2050 };
2051 if !state.frame_header.descriptor.content_checksum_flag() {
2052 return Ok(());
2053 }
2054 let Some(expected) = state.check_sum else {
2055 return Ok(());
2056 };
2057 let calculated = state.decoder_scratch.hash_finish() as u32;
2058 if expected != calculated {
2059 return Err(FrameDecoderError::ChecksumMismatch {
2060 expected,
2061 calculated,
2062 });
2063 }
2064 Ok(())
2065 }
2066
2067 /// Counter for how many bytes have been consumed while decoding the frame
2068 pub fn bytes_read_from_source(&self) -> u64 {
2069 let state = match &self.state {
2070 None => return 0,
2071 Some(s) => s,
2072 };
2073 state.bytes_read_counter
2074 }
2075
2076 /// Test-only: number of frames decoded through the single-copy direct
2077 /// path (`run_direct_decode`). Lets cross-module tests assert that a
2078 /// given decode took the decode-in-place path rather than the ring drain.
2079 #[cfg(test)]
2080 pub(crate) fn direct_frames(&self) -> u64 {
2081 self.direct_frames
2082 }
2083
2084 /// Test-only: whether the decode state currently holds an owning dictionary
2085 /// handle (`active_dict`). Every path that arms `Dict`-sourced scratch tables
2086 /// must also install this handle, or a later dict-table read resolves `None`.
2087 #[cfg(test)]
2088 pub(crate) fn active_dict_installed(&self) -> bool {
2089 self.state.as_ref().is_some_and(|s| s.active_dict.is_some())
2090 }
2091
2092 /// Whether the current frames last block has been decoded yet
2093 /// If this returns true you can call the drain* functions to get all content
2094 /// (the read() function will drain automatically if this returns true)
2095 pub fn is_finished(&self) -> bool {
2096 let state = match &self.state {
2097 None => return true,
2098 Some(s) => s,
2099 };
2100 if state.frame_header.descriptor.content_checksum_flag() {
2101 state.frame_finished && state.check_sum.is_some()
2102 } else {
2103 state.frame_finished
2104 }
2105 }
2106
2107 /// Counter for how many blocks have already been decoded
2108 pub fn blocks_decoded(&self) -> usize {
2109 let state = match &self.state {
2110 None => return 0,
2111 Some(s) => s,
2112 };
2113 state.block_counter
2114 }
2115
2116 /// Decodes blocks from a reader. It requires that the framedecoder has been initialized first.
2117 /// The Strategy influences how many blocks will be decoded before the function returns
2118 /// This is important if you want to manage memory consumption carefully. If you don't care
2119 /// about that you can just choose the strategy "All" and have all blocks of the frame decoded into the buffer
2120 pub fn decode_blocks(
2121 &mut self,
2122 mut source: impl Read,
2123 strat: BlockDecodingStrategy,
2124 ) -> Result<bool, FrameDecoderError> {
2125 use FrameDecoderError as err;
2126 // Apply the content-checksum mode to the streaming drain hash before
2127 // any block decodes into the ring. Hash only when a digest is both
2128 // wanted (mode != None) AND present in the frame (content_checksum_flag
2129 // set) — a flag-off frame has nothing to verify or expose, so hashing
2130 // it is wasted work. Mirrors the direct path and get_calculated_checksum.
2131 #[cfg(feature = "hash")]
2132 let checksum_mode = self.content_checksum;
2133 let state = self.state.as_mut().ok_or(err::NotYetInitialized)?;
2134 #[cfg(feature = "hash")]
2135 {
2136 let compute_hash = checksum_mode != ContentChecksum::None
2137 && state.frame_header.descriptor.content_checksum_flag();
2138 state.decoder_scratch.set_compute_hash(compute_hash);
2139 }
2140
2141 // Streaming entry point: pre-reserve the backing buffer to
2142 // the FCS-capped window plus a block so multi-block frames don't pay
2143 // repeated `reserve_amortized` grow steps (128 KiB → 256 KiB → ... →
2144 // window) as blocks accumulate, nor a copy of the window when it
2145 // fills. `decode_all` does the same up front in `decode_all_impl`;
2146 // this mirrors it for callers driving `decode_blocks` directly.
2147 // Idempotent — the backend's `reserve` early-returns when capacity
2148 // is already sufficient.
2149 state.reserve_decoding_buffer();
2150
2151 let mut block_dec = decoding::block_decoder::with_kernel(self.kernel);
2152
2153 let buffer_size_before = state.decoder_scratch.buffer_len();
2154 let block_counter_before = state.block_counter;
2155 loop {
2156 vprintln!("################");
2157 vprintln!("Next Block: {}", state.block_counter);
2158 vprintln!("################");
2159 // Capture the failing-block coordinates BEFORE the header read so
2160 // the error carries where it happened: `bytes_read_counter` is the
2161 // frame-absolute offset of this block's header (not yet advanced),
2162 // `block_counter` its 0-based index. Used by both the header- and
2163 // body-error builders below (block-precise recovery under `lsm`).
2164 let block_index = state.block_counter as u32;
2165 let block_frame_offset = state.bytes_read_counter as u32;
2166 let (block_header, block_header_size) =
2167 block_dec.read_block_header(&mut source).map_err(|source| {
2168 block_header_decode_error(source, block_index, block_frame_offset)
2169 })?;
2170 state.bytes_read_counter += u64::from(block_header_size);
2171
2172 vprintln!();
2173 vprintln!(
2174 "Found {} block with size: {}, which will be of size: {}",
2175 block_header.block_type,
2176 block_header.content_size,
2177 block_header.decompressed_size
2178 );
2179
2180 #[cfg(all(feature = "lsm", feature = "hash"))]
2181 let len_before_block: Option<usize> = if self.per_block_checksums_enabled {
2182 Some(state.decoder_scratch.buffer_len())
2183 } else {
2184 None
2185 };
2186 // Only expose the held dictionary while THIS frame is dict-backed
2187 // (`using_dict` is set per dict-apply, cleared on reset). A reused
2188 // decoder keeps `active_dict` across a no-dict frame for the
2189 // `ptr::eq` reuse-skip, so it must be gated here or a stray
2190 // out-of-window offset on a dictless frame would resolve against the
2191 // stale dictionary content instead of erroring.
2192 let dict_ref = if state.using_dict.is_some() {
2193 state.active_dict.as_ref().map(|h| h.as_dict())
2194 } else {
2195 None
2196 };
2197 let bytes_read_in_block_body = state
2198 .decoder_scratch
2199 .decode_block_content(&mut block_dec, &block_header, &mut source, dict_ref)
2200 .map_err(|source| {
2201 block_body_decode_error(
2202 source,
2203 block_index,
2204 block_frame_offset,
2205 &block_header,
2206 block_header_size,
2207 )
2208 })?;
2209 state.bytes_read_counter += bytes_read_in_block_body;
2210
2211 // Per-block XXH64 (low 32 bits) of the just-decompressed
2212 // bytes. Hashed from `last_n_as_slices` so RingBuffer wrap
2213 // is handled in-place, no extra copy.
2214 #[cfg(all(feature = "lsm", feature = "hash"))]
2215 if let Some(len_before_block) = len_before_block {
2216 let added = state.decoder_scratch.buffer_len() - len_before_block;
2217 let (s1, s2) = state.decoder_scratch.last_n_as_slices(added);
2218 let mut h = twox_hash::XxHash64::with_seed(0);
2219 use core::hash::Hasher;
2220 h.write(s1);
2221 h.write(s2);
2222 self.computed_block_checksums.push(h.finish() as u32);
2223 }
2224
2225 state.block_counter += 1;
2226
2227 vprintln!("Output: {}", state.decoder_scratch.buffer_len());
2228
2229 if block_header.last_block {
2230 state.frame_finished = true;
2231 if state.frame_header.descriptor.content_checksum_flag() {
2232 let mut chksum = [0u8; 4];
2233 source
2234 .read_exact(&mut chksum)
2235 .map_err(err::FailedToReadChecksum)?;
2236 state.bytes_read_counter += 4;
2237 let chksum = u32::from_le_bytes(chksum);
2238 state.check_sum = Some(chksum);
2239 }
2240 break;
2241 }
2242
2243 match strat {
2244 BlockDecodingStrategy::All => { /* keep going */ }
2245 BlockDecodingStrategy::UptoBlocks(n) => {
2246 if state.block_counter - block_counter_before >= n {
2247 break;
2248 }
2249 }
2250 BlockDecodingStrategy::UptoBytes(n) => {
2251 if state.decoder_scratch.buffer_len() - buffer_size_before >= n {
2252 break;
2253 }
2254 }
2255 }
2256 }
2257
2258 Ok(state.frame_finished)
2259 }
2260
2261 /// Decode the inner blocks `[start_block, end_block)` of the current
2262 /// frame and return their decompressed bytes as one contiguous buffer.
2263 ///
2264 /// Serves two consumer needs with one call:
2265 ///
2266 /// - **Range-query performance:** decode only the inner zstd blocks that
2267 /// cover a key range instead of the whole frame. Blocks before
2268 /// `start_block` are decoded into the window (zstd blocks share one
2269 /// window, so a leading block's bytes may be the match source for an
2270 /// in-range block and cannot simply be skipped) but their output is not
2271 /// returned; blocks at or after `end_block` are not decoded at all,
2272 /// which is the trailing-block work saving. Map a decompressed byte
2273 /// offset to a block index with
2274 /// [`FrameEmitInfo::decompressed_byte_range`].
2275 /// - **Best-effort recovery:** if a block decode fails, decoding stops,
2276 /// the clean prefix of in-range output is preserved in
2277 /// [`PartialDecode::data`], and the failure is reported via
2278 /// [`PartialDecode::stopped_at`]. Passing `(0, u32::MAX)` decodes the
2279 /// whole frame, stopping at the first corrupt block (pure recovery).
2280 ///
2281 /// `end_block` is exclusive; pass `u32::MAX` to decode to the end of the
2282 /// frame. Call on a freshly [`reset`](Self::reset) decoder (it decodes
2283 /// from the frame's first block).
2284 ///
2285 /// # Resume (cold incremental / top-up)
2286 ///
2287 /// A plain call drains its in-range output from the match window on return,
2288 /// so two consecutive calls cannot resume one another and growing a decoded
2289 /// extent would mean re-decoding the covering prefix from block 0
2290 /// (`O(extent)` per growth, `O(N²)` for a forward walk). The `resume` /
2291 /// `emit_resume` arguments make a symmetric one-call grow-loop possible:
2292 ///
2293 /// - `emit_resume = true` captures the cross-block carry-over state (entropy
2294 /// tables + repcode history + the next block index / output offset) into
2295 /// [`PartialDecode::resume_state`]. The entropy-table snapshot clone is
2296 /// only paid when this is set. The snapshot is `None` when the decode
2297 /// reaches the frame's last block ([`PartialDecode::frame_finished`]):
2298 /// there is no following block to resume from, so an incremental walk
2299 /// stops on `frame_finished` rather than on a `None` snapshot.
2300 /// - `resume = Some(`[`ResumeInput`]`)` continues from a previously emitted
2301 /// [`ResumeState`] WITHOUT re-decompressing the preceding blocks: the
2302 /// match window is primed from [`ResumeInput::window_prime`] and the
2303 /// entropy/repcode tables are restored from the state, so a `Repeat_Mode`
2304 /// resume block resolves byte-identically to a contiguous decode — even
2305 /// across a dropped (cold) decoder.
2306 ///
2307 /// When `resume` is `Some`, decoding resumes at
2308 /// [`ResumeState::block_index`] and the `start_block` argument is ignored
2309 /// (pass `resume.state.block_index()`); position `source` at that block's
2310 /// compressed frame offset
2311 /// ([`FrameEmitInfo::blocks`]`[block_index].offset_in_frame`). After a
2312 /// resumed call, [`bytes_read_from_source`](Self::bytes_read_from_source)
2313 /// and any `stopped_at` offsets are relative to the repositioned `source`.
2314 ///
2315 /// **Dictionaries:** [`ResumeState`] does NOT carry the dictionary content.
2316 /// For a dictionary frame, attach the dictionary to the resuming decoder the
2317 /// same way as for a fresh decode — [`reset`](Self::reset) with the
2318 /// dictionary registered (or
2319 /// [`reset_with_dict_handle`](Self::reset_with_dict_handle)) BEFORE this
2320 /// call — so dict-sourced matches near the frame start resolve. The caller
2321 /// already holds the dictionary (it supplied it at encode time), so
2322 /// re-supplying it on resume is free; storing it in the snapshot would only
2323 /// duplicate it. The resume guard records the applied dictionary's identity
2324 /// and rejects ([`FrameDecoderError::ResumeFrameMismatch`]) a resume whose
2325 /// active dictionary differs from the one the snapshot was captured under.
2326 ///
2327 /// # Errors
2328 ///
2329 /// Returns [`FrameDecoderError::NotYetInitialized`] if the decoder has not
2330 /// been reset, [`FrameDecoderError::InvalidBlockRange`] if the effective
2331 /// start exceeds `end_block`, [`FrameDecoderError::ResumeWindowTooShort`]
2332 /// if `resume`'s `window_prime` is shorter than the match window the resume
2333 /// block can reach back into (`min(window_size, output_offset)`), and
2334 /// [`FrameDecoderError::ResumeFrameMismatch`] if the snapshot was captured
2335 /// from a frame with a different decode shape / dictionary, or (with the
2336 /// `hash` feature) a `window_prime` whose content does not match what was
2337 /// captured — all rejected up front rather than silently mis-resolving
2338 /// matches. A corrupt block is NOT an `Err` here: it is reported via
2339 /// [`PartialDecode::stopped_at`] so the clean prefix survives.
2340 ///
2341 /// [`FrameEmitInfo::decompressed_byte_range`]: crate::encoding::frame_emit_info::FrameEmitInfo::decompressed_byte_range
2342 /// [`FrameEmitInfo::blocks`]: crate::encoding::frame_emit_info::FrameEmitInfo::blocks
2343 #[cfg(feature = "lsm")]
2344 #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
2345 pub fn decode_blocks_partial(
2346 &mut self,
2347 mut source: impl Read,
2348 start_block: u32,
2349 end_block: u32,
2350 resume: Option<ResumeInput<'_>>,
2351 emit_resume: bool,
2352 ) -> Result<PartialDecode, FrameDecoderError> {
2353 use FrameDecoderError as err;
2354 #[cfg(feature = "hash")]
2355 let checksum_mode = self.content_checksum;
2356 let magicless = self.magicless;
2357 let kernel = self.kernel;
2358 let state = self.state.as_mut().ok_or(err::NotYetInitialized)?;
2359
2360 // Honor the checksum mode before any drain/read can hash: `None` must
2361 // compute no XXH64. `decode_blocks` sets this; the partial path must too,
2362 // or a reused scratch keeps hashing with the default-enabled state.
2363 #[cfg(feature = "hash")]
2364 {
2365 let compute_hash = checksum_mode != ContentChecksum::None
2366 && state.frame_header.descriptor.content_checksum_flag();
2367 state.decoder_scratch.set_compute_hash(compute_hash);
2368 }
2369
2370 // A dictionary that carries no ID cannot be told from another one, and
2371 // the frame key records only that ID: two different raw-content
2372 // dictionaries key alike, so a snapshot would be restored under the
2373 // wrong one — and one taken here could later be. Both directions are
2374 // refused, and refused HERE, before a block is read or a buffer
2375 // reserved. An answer that does not depend on the blocks must not be
2376 // given after decoding them: it would discard the output they produced
2377 // and leave the source and the decoder somewhere the caller cannot
2378 // retry from.
2379 if (resume.is_some() || emit_resume) && state.using_dict == Some(0) {
2380 return Err(err::ResumeUnidentifiedDictionary);
2381 }
2382
2383 // Mirror `decode_blocks`: pre-reserve the backing buffer to the
2384 // FCS-capped window plus a block so multi-block frames don't pay
2385 // repeated grow steps. The RAW frame window stays separately bound —
2386 // the resume logic below bounds match reach by the frame's window
2387 // semantics, not by the (possibly smaller) reservation cap.
2388 let window_size = state.frame_header.window_size().unwrap_or(0) as usize;
2389 state.reserve_decoding_buffer();
2390
2391 // Cold resume: prime the match window + restore entropy/repcode state +
2392 // advance the block cursor BEFORE the loop, so the first in-range block
2393 // resolves its matches and `Repeat_Mode` tables against the caller's
2394 // persisted state instead of re-decoded prefix blocks. The effective
2395 // start is the resume state's block index (the passed `start_block` is
2396 // ignored in resume mode, per the doc).
2397 let effective_start = if let Some(r) = resume {
2398 // Reject a snapshot captured from a different frame shape BEFORE
2399 // touching any decoder state: restoring entropy/repcode tables that
2400 // belong to another frame would silently produce byte-wrong output.
2401 let current_key = FrameKey::from_state(state, magicless);
2402 if current_key != r.state.frame_key {
2403 return Err(err::ResumeFrameMismatch);
2404 }
2405 let output_offset = r.state.output_offset;
2406 // The window the resume block can reach back into is bounded by the
2407 // smaller of the frame's window_size and the bytes produced so far.
2408 let required = core::cmp::min(window_size as u64, output_offset) as usize;
2409 if r.window_prime.len() < required {
2410 return Err(err::ResumeWindowTooShort {
2411 got: r.window_prime.len(),
2412 need: required,
2413 });
2414 }
2415 // Only the most recent `window_size` bytes can ever back a match
2416 // (offset <= window_size by the frame invariant); load just those
2417 // even if the caller handed us a longer prefix, bounding resume
2418 // memory to one window regardless of the skipped prefix's size.
2419 let prime = if r.window_prime.len() > window_size {
2420 &r.window_prime[r.window_prime.len() - window_size..]
2421 } else {
2422 r.window_prime
2423 };
2424 // Content-exact identity: the primed window must hash to what was
2425 // captured at emit. Catches a same-shape-but-different-frame
2426 // snapshot and a wrong/corrupted window_prime (which FrameKey alone
2427 // cannot), before any state is restored. O(window) one-time per
2428 // resume — negligible next to the decode it guards.
2429 #[cfg(feature = "hash")]
2430 if xxh64_of(prime) != r.state.window_hash {
2431 return Err(err::ResumeFrameMismatch);
2432 }
2433 // Validate the effective range (resume mode begins at the resume
2434 // block, ignoring the caller's `start_block`) BEFORE mutating the
2435 // decoder: an inverted `end_block` must fail without priming the
2436 // window / entropy or advancing the cursor, leaving the decoder
2437 // re-resettable rather than in a half-resumed state.
2438 let effective_start = r.state.block_index;
2439 if effective_start > end_block {
2440 return Err(err::InvalidBlockRange {
2441 start_block: effective_start,
2442 end_block,
2443 });
2444 }
2445 state.decoder_scratch.restore_entropy(r.state);
2446 state
2447 .decoder_scratch
2448 .prime_window(prime, output_offset, kernel);
2449 state.block_counter = effective_start as usize;
2450 // The caller repositions `source` to the resume block; report
2451 // consumed bytes relative to that point (reset left this at the
2452 // frame-header size).
2453 state.bytes_read_counter = 0;
2454 effective_start
2455 } else {
2456 // Fresh decode: validate the caller's range (no state to mutate).
2457 if start_block > end_block {
2458 return Err(err::InvalidBlockRange {
2459 start_block,
2460 end_block,
2461 });
2462 }
2463 start_block
2464 };
2465
2466 let mut block_dec = decoding::block_decoder::with_kernel(self.kernel);
2467
2468 // Bytes of prefix-window output that physically precede the first
2469 // in-range block in the buffer. Captured at the prefix → in-range
2470 // transition (after leading blocks were dropped to the window) so we
2471 // can discard exactly those bytes once decoding is done. `None` until
2472 // the first in-range block is reached.
2473 let mut prefix_window_len: Option<usize> = None;
2474 // Exact count of clean in-range decompressed bytes (sum of per-block
2475 // length deltas of the in-range blocks that succeeded). Any partial
2476 // bytes of a failing in-range block are excluded — the fused executor
2477 // rolls the buffer back to the pre-block checkpoint on a sequence
2478 // error, and anything left over is never counted here, so it is not
2479 // drained into `data`.
2480 let mut subset_bytes: u64 = 0;
2481 let mut blocks_decoded: u32 = 0;
2482 let mut stopped_at: Option<(u32, FrameDecoderError)> = None;
2483
2484 loop {
2485 let block_index = state.block_counter as u32;
2486 // Stop before decoding `end_block`: the trailing blocks are never
2487 // touched (the perf win), and the frame's tail is left unread.
2488 if block_index >= end_block || state.frame_finished {
2489 break;
2490 }
2491 let in_range = block_index >= effective_start;
2492 // Snapshot the window length at the prefix → in-range boundary.
2493 if in_range && prefix_window_len.is_none() {
2494 prefix_window_len = Some(state.decoder_scratch.buffer_len());
2495 }
2496
2497 let block_frame_offset = state.bytes_read_counter as u32;
2498 let (block_header, block_header_size) = match block_dec.read_block_header(&mut source) {
2499 Ok(v) => v,
2500 Err(e) => {
2501 stopped_at = Some((
2502 block_index,
2503 block_header_decode_error(e, block_index, block_frame_offset),
2504 ));
2505 break;
2506 }
2507 };
2508 state.bytes_read_counter += u64::from(block_header_size);
2509
2510 let len_before = state.decoder_scratch.buffer_len();
2511 // Only expose the held dictionary while THIS frame is dict-backed
2512 // (`using_dict` is set per dict-apply, cleared on reset). A reused
2513 // decoder keeps `active_dict` across a no-dict frame for the
2514 // `ptr::eq` reuse-skip, so it must be gated here or a stray
2515 // out-of-window offset on a dictless frame would resolve against the
2516 // stale dictionary content instead of erroring.
2517 let dict_ref = if state.using_dict.is_some() {
2518 state.active_dict.as_ref().map(|h| h.as_dict())
2519 } else {
2520 None
2521 };
2522 match state.decoder_scratch.decode_block_content(
2523 &mut block_dec,
2524 &block_header,
2525 &mut source,
2526 dict_ref,
2527 ) {
2528 Ok(body_read) => state.bytes_read_counter += body_read,
2529 Err(e) => {
2530 stopped_at = Some((
2531 block_index,
2532 block_body_decode_error(
2533 e,
2534 block_index,
2535 block_frame_offset,
2536 &block_header,
2537 block_header_size,
2538 ),
2539 ));
2540 break;
2541 }
2542 }
2543 let produced = state.decoder_scratch.buffer_len() - len_before;
2544 // Per-block XXH64 capture, mirroring `decode_blocks`: hash this
2545 // block's just-decoded bytes BEFORE any window drop so the digest
2546 // count stays 1:1 with the blocks decoded on this path too. Covers
2547 // context (out-of-range) blocks as well, matching `decode_blocks`
2548 // which hashes every block it decodes.
2549 #[cfg(all(feature = "lsm", feature = "hash"))]
2550 if self.per_block_checksums_enabled {
2551 use core::hash::Hasher;
2552 let (s1, s2) = state.decoder_scratch.last_n_as_slices(produced);
2553 let mut h = twox_hash::XxHash64::with_seed(0);
2554 h.write(s1);
2555 h.write(s2);
2556 self.computed_block_checksums.push(h.finish() as u32);
2557 }
2558 state.block_counter += 1;
2559 if in_range {
2560 subset_bytes += produced as u64;
2561 blocks_decoded += 1;
2562 }
2563
2564 if block_header.last_block {
2565 state.frame_finished = true;
2566 if state.frame_header.descriptor.content_checksum_flag() {
2567 let mut chksum = [0u8; 4];
2568 match source.read_exact(&mut chksum) {
2569 Ok(()) => {
2570 state.bytes_read_counter += 4;
2571 state.check_sum = Some(u32::from_le_bytes(chksum));
2572 }
2573 // A trailing-checksum read failure does not invalidate
2574 // the decoded bytes; surface it so the caller knows the
2575 // frame tail was truncated, but keep `data`.
2576 Err(e) => {
2577 stopped_at = Some((block_index, err::FailedToReadChecksum(e)));
2578 }
2579 }
2580 }
2581 break;
2582 }
2583
2584 // Leading (out-of-range) block: bound memory to the window. We
2585 // must NOT drop once in-range, or the in-range output we are about
2586 // to return would be discarded.
2587 if !in_range {
2588 state.decoder_scratch.buffer_drop_to_window_size();
2589 }
2590 }
2591
2592 // Emit cross-block carry-over state for a later resume, if requested.
2593 // Captured AFTER the loop (entropy tables / repcode history are final)
2594 // but BEFORE the drain — the drain only touches the visible output, not
2595 // the entropy state or `total_output_counter`. `block_counter` /
2596 // `total_output()` give the resume coordinates: the next block to decode
2597 // and the cumulative decompressed offset before it (clean even after an
2598 // early stop, since a failed block rolls both back to its checkpoint).
2599 // Suppress the snapshot on the terminal block: `block_counter` is then
2600 // one past the last block (EOF), for which there is no next-block source
2601 // position to resume from. A resume needs a real following block.
2602 let resume_state = if emit_resume && !state.frame_finished {
2603 let dict_ref = if state.using_dict.is_some() {
2604 state.active_dict.as_ref().map(|h| h.as_dict())
2605 } else {
2606 None
2607 };
2608 let (fse, huf, offset_hist) = state.decoder_scratch.export_entropy(dict_ref);
2609 Some(ResumeState {
2610 frame_key: FrameKey::from_state(state, magicless),
2611 block_index: state.block_counter as u32,
2612 output_offset: state.decoder_scratch.total_output(),
2613 fse,
2614 huf,
2615 offset_hist,
2616 #[cfg(feature = "hash")]
2617 window_hash: state.decoder_scratch.window_tail_hash(window_size),
2618 })
2619 } else {
2620 None
2621 };
2622
2623 // The visible buffer is now `[prefix window][in-range clean][maybe
2624 // trailing garbage from a failed in-range block]`. Drop the prefix
2625 // window from the front (match resolution is complete, so it is no
2626 // longer needed), then drain exactly the clean in-range byte count.
2627 let w = prefix_window_len.unwrap_or(0);
2628 state.decoder_scratch.buffer_discard_front(w);
2629 let mut data = alloc::vec![0u8; subset_bytes as usize];
2630 state
2631 .decoder_scratch
2632 .buffer_read_all(&mut data)
2633 .map_err(err::FailedToDrainDecodebuffer)?;
2634
2635 // Clear anything still buffered so a later `read()`/`collect()` on this
2636 // decoder cannot surface out-of-range bytes: the leading-block window
2637 // when no in-range block was reached (`prefix_window_len` stayed
2638 // `None`, so `w` was 0), or trailing garbage from a failed in-range
2639 // block. Only the returned `data` is the partial decode's output.
2640 let residual = state.decoder_scratch.buffer_len();
2641 state.decoder_scratch.buffer_discard_front(residual);
2642
2643 Ok(PartialDecode {
2644 data,
2645 start_block: effective_start,
2646 blocks_decoded,
2647 stopped_at,
2648 frame_finished: state.frame_finished,
2649 resume_state,
2650 })
2651 }
2652
2653 /// Collect bytes and retain window_size bytes while decoding is still going on.
2654 /// After decoding of the frame (is_finished() == true) has finished it will collect all remaining bytes
2655 pub fn collect(&mut self) -> Option<Vec<u8>> {
2656 let finished = self.is_finished();
2657 let state = self.state.as_mut()?;
2658 if finished {
2659 Some(state.decoder_scratch.buffer_drain())
2660 } else {
2661 state.decoder_scratch.buffer_drain_to_window_size()
2662 }
2663 }
2664
2665 /// Collect bytes and retain window_size bytes while decoding is still going on.
2666 /// After decoding of the frame (is_finished() == true) has finished it will collect all remaining bytes
2667 pub fn collect_to_writer(&mut self, w: impl Write) -> Result<usize, Error> {
2668 let finished = self.is_finished();
2669 let state = match &mut self.state {
2670 None => return Ok(0),
2671 Some(s) => s,
2672 };
2673 if finished {
2674 state.decoder_scratch.buffer_drain_to_writer(w)
2675 } else {
2676 state.decoder_scratch.buffer_drain_to_window_size_writer(w)
2677 }
2678 }
2679
2680 /// How many bytes can currently be collected from the decodebuffer, while decoding is going on this will be lower than the actual decodbuffer size
2681 /// because window_size bytes need to be retained for decoding.
2682 /// After decoding of the frame (is_finished() == true) has finished it will report all remaining bytes
2683 pub fn can_collect(&self) -> usize {
2684 let finished = self.is_finished();
2685 let state = match &self.state {
2686 None => return 0,
2687 Some(s) => s,
2688 };
2689 if finished {
2690 state.decoder_scratch.buffer_can_drain()
2691 } else {
2692 state
2693 .decoder_scratch
2694 .buffer_can_drain_to_window_size()
2695 .unwrap_or(0)
2696 }
2697 }
2698
2699 /// Decodes blocks from the source slice and reads from the decodebuffer into the target slice, one block at a
2700 /// time: output is handed to `target` as each block completes, and no further block is decoded while `target`
2701 /// cannot take what is already decoded. The decode buffer so holds one window plus one block however much input
2702 /// is supplied; call again with the unread input to continue.
2703 /// The source slice may contain only parts of a frame but must contain at least one full block to make progress
2704 ///
2705 /// By all means use decode_blocks if you have a io.Reader available. This is just for compatibility with other decompressors
2706 /// which try to serve an old-style c api
2707 ///
2708 /// Returns (read, written). Both zero means the call made no progress: the
2709 /// source holds no full block and the buffer no drainable output, so the
2710 /// same input cannot advance. `read == 0` with `written > 0` is progress of
2711 /// the other kind: `target` filled from output already buffered, and the
2712 /// same input decodes further once the caller offers more room.
2713 ///
2714 /// Note that no kind of block can be bigger than 128kb.
2715 /// 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
2716 ///
2717 /// 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)
2718 pub fn decode_from_to(
2719 &mut self,
2720 source: &[u8],
2721 target: &mut [u8],
2722 ) -> Result<(usize, usize), FrameDecoderError> {
2723 let progress = self.decode_available(source, target, false)?;
2724 // Once the frame is fully decoded and drained, its length and running
2725 // digest are final: check the declared size, and the checksum in
2726 // `Verify` mode (no-op otherwise).
2727 if self.is_finished() && self.can_collect() == 0 {
2728 self.verify_content_size()?;
2729 #[cfg(feature = "hash")]
2730 self.verify_content_checksum()?;
2731 }
2732 Ok(progress)
2733 }
2734
2735 /// [`Self::decode_from_to`] without its finish-point checks, for a caller
2736 /// that must not report an error in the same call that delivered bytes
2737 /// (a `Read` adapter) and so runs them itself on a call that delivers
2738 /// none. `reserve_window` sizes the buffer for a frame of unknown size to
2739 /// its window at its first block instead of letting it grow.
2740 pub(crate) fn decode_available(
2741 &mut self,
2742 source: &[u8],
2743 target: &mut [u8],
2744 reserve_window: bool,
2745 ) -> Result<(usize, usize), FrameDecoderError> {
2746 use FrameDecoderError as err;
2747 let bytes_read_at_start = match &self.state {
2748 Some(s) => s.bytes_read_counter,
2749 None => 0,
2750 };
2751 // Bytes already handed to `target` by the per-block drain below.
2752 let mut written = 0usize;
2753
2754 if !self.is_finished() || self.state.is_none() {
2755 let mut mt_source = source;
2756
2757 if self.state.is_none() {
2758 self.init(&mut mt_source)?;
2759 }
2760
2761 //pseudo block to scope "state" so we can borrow self again after the block
2762 {
2763 let kernel = self.kernel;
2764 let state = match &mut self.state {
2765 Some(s) => s,
2766 None => panic!("Bug in library"),
2767 };
2768 let mut block_dec = decoding::block_decoder::with_kernel(kernel);
2769
2770 // Honour the content-checksum mode on this hand-rolled decode
2771 // loop (it does not go through `decode_blocks`): hash only when
2772 // a digest is wanted and the frame carries one. `None` skips the
2773 // XXH64 pass; verification happens after the final drain below.
2774 #[cfg(feature = "hash")]
2775 {
2776 let compute_hash = self.content_checksum != ContentChecksum::None
2777 && state.frame_header.descriptor.content_checksum_flag();
2778 state.decoder_scratch.set_compute_hash(compute_hash);
2779 }
2780
2781 if state.frame_header.descriptor.content_checksum_flag()
2782 && state.frame_finished
2783 && state.check_sum.is_none()
2784 {
2785 // The trailing checksum arrived on a separate call (the last
2786 // block finished earlier). Consume it and fall through to the
2787 // shared `self.read` + post-drain verify below — NOT an early
2788 // return — so any output still buffered from a prior
2789 // small-`target` call is flushed on this call too, and the
2790 // checksum is verified through the one shared path.
2791 if mt_source.len() >= 4 {
2792 let chksum = mt_source[..4].try_into().expect("optimized away");
2793 state.bytes_read_counter += 4;
2794 let chksum = u32::from_le_bytes(chksum);
2795 state.check_sum = Some(chksum);
2796 mt_source = &mt_source[4..];
2797 }
2798 }
2799
2800 loop {
2801 // The frame is fully decoded (last block seen, trailer
2802 // consumed above); no more blocks to read. Any leftover
2803 // bytes are not a block header — stop before misreading them.
2804 if state.frame_finished {
2805 break;
2806 }
2807 // Hand what the window no longer needs to `target` before
2808 // decoding more, and decode no further while `target` cannot
2809 // take it: the buffer then holds one window plus the block
2810 // being decoded, whatever the caller supplies, as upstream
2811 // `ZSTD_decompressStream` flushes each block before the next.
2812 let (read, pending) = state
2813 .decoder_scratch
2814 .buffer_read_reporting_pending(&mut target[written..])
2815 .map_err(err::FailedToDrainDecodebuffer)?;
2816 written += read;
2817 // Stop on a full target as well as on output left behind:
2818 // a drain that empties the buffer into the last of `target`
2819 // leaves nothing pending, and decoding another block then
2820 // consumes input the caller cannot be handed the output of.
2821 // A target of no bytes is not full in that sense: it starts
2822 // at its own length, so the test would fire before any block
2823 // was read and a frame that produces nothing could never
2824 // reach the empty block that ends it. Such a frame decodes
2825 // here; one that does produce bytes buffers its first block
2826 // and stops on the `pending` arm of the next pass.
2827 if pending > 0 || (!target.is_empty() && written == target.len()) {
2828 break;
2829 }
2830 //check if there are enough bytes for the next header
2831 if mt_source.len() < 3 {
2832 break;
2833 }
2834 let block_index = state.block_counter as u32;
2835 let block_frame_offset = state.bytes_read_counter as u32;
2836 let (block_header, block_header_size) = block_dec
2837 .read_block_header(&mut mt_source)
2838 .map_err(|source| {
2839 block_header_decode_error(source, block_index, block_frame_offset)
2840 })?;
2841
2842 // check the needed size for the block before updating counters.
2843 // 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
2844 if mt_source.len() < block_header.content_size as usize {
2845 break;
2846 }
2847 state.bytes_read_counter += u64::from(block_header_size);
2848 // A frame that declares its size gets its buffer in one
2849 // allocation once its first block is in hand, as upstream
2850 // allocates its stream buffer per frame: growing it block by
2851 // block cost a fresh decoder several reallocations, copies
2852 // and page-fault passes per frame. Not on the header alone,
2853 // which would let a header followed by nothing reserve its
2854 // whole declared window. The size is content-capped, so a
2855 // small frame gets a small buffer. A frame of unknown size
2856 // gets its window only when the caller asked for it: the
2857 // `Read` adapter does, as `decode_blocks` always has, since
2858 // growing a large frame by doubling copies it several times;
2859 // the slice API leaves it to grow, so a small unsized frame
2860 // does not pay for a window it never fills.
2861 if state.block_counter == 0
2862 && (reserve_window || state.frame_header.fcs_declared())
2863 {
2864 state.reserve_decoding_buffer();
2865 }
2866
2867 // Only expose the held dictionary while THIS frame is dict-backed
2868 // (`using_dict` is set per dict-apply, cleared on reset). A reused
2869 // decoder keeps `active_dict` across a no-dict frame for the
2870 // `ptr::eq` reuse-skip, so it must be gated here or a stray
2871 // out-of-window offset on a dictless frame would resolve against the
2872 // stale dictionary content instead of erroring.
2873 let dict_ref = if state.using_dict.is_some() {
2874 state.active_dict.as_ref().map(|h| h.as_dict())
2875 } else {
2876 None
2877 };
2878 #[cfg(all(feature = "lsm", feature = "hash"))]
2879 let len_before_block = self
2880 .per_block_checksums_enabled
2881 .then(|| state.decoder_scratch.buffer_len());
2882 // The whole block is in `mt_source` (checked above), so
2883 // it decodes from the slice without a copy.
2884 let bytes_read_in_block_body = state
2885 .decoder_scratch
2886 .decode_block_content_from_slice(
2887 &mut block_dec,
2888 &block_header,
2889 &mut mt_source,
2890 dict_ref,
2891 )
2892 .map_err(|source| {
2893 block_body_decode_error(
2894 source,
2895 block_index,
2896 block_frame_offset,
2897 &block_header,
2898 block_header_size,
2899 )
2900 })?;
2901 state.bytes_read_counter += bytes_read_in_block_body;
2902 // The block's digest, as `decode_blocks` takes it: output
2903 // is drained before a block decodes, never during, so the
2904 // whole block is still in the buffer here.
2905 #[cfg(all(feature = "lsm", feature = "hash"))]
2906 if let Some(len_before_block) = len_before_block {
2907 let added = state.decoder_scratch.buffer_len() - len_before_block;
2908 let (s1, s2) = state.decoder_scratch.last_n_as_slices(added);
2909 let mut h = twox_hash::XxHash64::with_seed(0);
2910 use core::hash::Hasher;
2911 h.write(s1);
2912 h.write(s2);
2913 self.computed_block_checksums.push(h.finish() as u32);
2914 }
2915 state.block_counter += 1;
2916
2917 if block_header.last_block {
2918 state.frame_finished = true;
2919 if state.frame_header.descriptor.content_checksum_flag() {
2920 //if there are enough bytes handle this here. Else the block at the start of this function will handle it at the next call
2921 if mt_source.len() >= 4 {
2922 let chksum = mt_source[..4].try_into().expect("optimized away");
2923 state.bytes_read_counter += 4;
2924 let chksum = u32::from_le_bytes(chksum);
2925 state.check_sum = Some(chksum);
2926 }
2927 }
2928 break;
2929 }
2930 }
2931 }
2932 }
2933
2934 let result_len = written
2935 + self
2936 .read(&mut target[written..])
2937 .map_err(err::FailedToDrainDecodebuffer)?;
2938 let bytes_read_at_end = match &mut self.state {
2939 Some(s) => s.bytes_read_counter,
2940 None => panic!("Bug in library"),
2941 };
2942 let read_len = bytes_read_at_end - bytes_read_at_start;
2943 Ok((read_len as usize, result_len))
2944 }
2945
2946 /// Decode multiple frames into the output slice.
2947 ///
2948 /// `input` must contain an exact number of frames. Skippable frames are allowed and will be
2949 /// skipped during decode.
2950 ///
2951 /// `output` must be large enough to hold the decompressed data. If you don't know
2952 /// how large the output will be, use [`FrameDecoder::decode_blocks`] instead.
2953 ///
2954 /// This calls [`FrameDecoder::init`], and all bytes currently in the decoder will be lost.
2955 ///
2956 /// Returns the number of bytes written to `output`.
2957 pub fn decode_all(
2958 &mut self,
2959 input: &[u8],
2960 output: &mut [u8],
2961 ) -> Result<usize, FrameDecoderError> {
2962 #[cfg(not(feature = "lsm"))]
2963 {
2964 self.decode_all_impl(input, output, |this, src| this.reset_from_slice(src))
2965 }
2966 #[cfg(feature = "lsm")]
2967 {
2968 self.decode_all_impl(input, output, |this, src| this.reset_from_slice(src), None)
2969 }
2970 }
2971
2972 /// Decode multiple frames into the output slice, invoking `visitor`
2973 /// for every skippable frame encountered before advancing past it.
2974 ///
2975 /// `input` must contain an exact number of frames. Skippable frames
2976 /// (RFC 8878 §3.1.2 magic numbers `0x184D2A50..=0x184D2A5F`) are
2977 /// allowed and will be both visited AND skipped: the visitor gets
2978 /// `(magic_variant, payload)` where `magic_variant` is the low
2979 /// nibble of the magic (`magic - 0x184D2A50`, range `0..=15`) and
2980 /// `payload` is a borrowed slice of the on-wire payload bytes (the
2981 /// skippable frame's `Frame_Size` field worth of data) into
2982 /// `input` — no allocation.
2983 ///
2984 /// The visitor sees skippable frames in stream order; interleaved
2985 /// regular zstd frames continue to decompress into `output` exactly
2986 /// as `decode_all` does.
2987 ///
2988 /// `output` must be large enough to hold the decompressed data.
2989 /// Returns the number of bytes written to `output`.
2990 ///
2991 /// # Example
2992 ///
2993 /// ```ignore
2994 /// use structured_zstd::decoding::FrameDecoder;
2995 ///
2996 /// let mut decoder = FrameDecoder::new();
2997 /// let mut output = vec![0u8; 1024];
2998 /// let mut collected: Vec<(u8, Vec<u8>)> = Vec::new();
2999 /// let n = decoder.decode_all_with_skippable_visitor(
3000 /// input,
3001 /// &mut output,
3002 /// |variant, payload| collected.push((variant, payload.to_vec())),
3003 /// )?;
3004 /// ```
3005 #[cfg(feature = "lsm")]
3006 #[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
3007 pub fn decode_all_with_skippable_visitor<F>(
3008 &mut self,
3009 input: &[u8],
3010 output: &mut [u8],
3011 mut visitor: F,
3012 ) -> Result<usize, FrameDecoderError>
3013 where
3014 F: FnMut(u8, &[u8]),
3015 {
3016 self.decode_all_impl(
3017 input,
3018 output,
3019 |this, src| this.reset_from_slice(src),
3020 Some(&mut visitor),
3021 )
3022 }
3023
3024 /// Decode multiple frames into the output slice using a pre-parsed dictionary handle.
3025 ///
3026 /// `input` must contain an exact number of frames. Skippable frames are allowed and will be
3027 /// skipped during decode.
3028 ///
3029 /// `output` must be large enough to hold the decompressed data. If you don't know
3030 /// how large the output will be, use [`FrameDecoder::decode_blocks`] instead.
3031 ///
3032 /// This calls [`FrameDecoder::init_with_dict_handle`], and all bytes currently in the
3033 /// decoder will be lost.
3034 ///
3035 /// # Warning
3036 ///
3037 /// Each decoded frame is initialized with `dict`, even when a frame header
3038 /// omits the optional dictionary ID. Callers must only use this API when
3039 /// they already know the input frames were encoded with the provided
3040 /// dictionary; otherwise decoded output can be silently corrupted.
3041 pub fn decode_all_with_dict_handle(
3042 &mut self,
3043 input: &[u8],
3044 output: &mut [u8],
3045 dict: &DictionaryHandle,
3046 ) -> Result<usize, FrameDecoderError> {
3047 #[cfg(not(feature = "lsm"))]
3048 {
3049 self.decode_all_impl(input, output, |this, src| {
3050 this.reset_from_slice_with_dict_handle(src, dict)
3051 })
3052 }
3053 #[cfg(feature = "lsm")]
3054 {
3055 self.decode_all_impl(
3056 input,
3057 output,
3058 |this, src| this.reset_from_slice_with_dict_handle(src, dict),
3059 None,
3060 )
3061 }
3062 }
3063
3064 /// Whether the decoder sits at the very start of an initialised frame:
3065 /// the header has been read (state populated) but no block has been
3066 /// decoded and the frame is not finished. In this state the wrapped
3067 /// source is positioned exactly after the frame header, so
3068 /// [`Self::decode_current_frame_to_vec`] can decode the rest of the frame
3069 /// straight from the remaining source bytes.
3070 pub(crate) fn is_at_frame_start(&self) -> bool {
3071 self.state
3072 .as_ref()
3073 .is_some_and(|s| s.block_counter == 0 && !s.frame_finished)
3074 }
3075
3076 /// Decode the CURRENT (already-initialised) frame, APPENDING the
3077 /// decompressed bytes to `output`, and return the number appended.
3078 ///
3079 /// `input` must be the frame's post-header bytes (the wrapped source after
3080 /// `init` consumed the header). Unlike [`Self::decode_all_to_vec`] this
3081 /// neither re-reads a header nor requires the caller to pre-reserve
3082 /// capacity: a frame that declares its content size decodes DIRECTLY into
3083 /// freshly-grown `output` capacity via the single-copy direct path
3084 /// ([`Self::run_direct_decode`]) — bypassing the `Ring`/`FlatBuf` →
3085 /// `read()` drain copy the streaming loop pays — while an unsized frame
3086 /// falls back to the window-bounded ring drain (still one copy, into
3087 /// `output`). Backs [`StreamingDecoder`](crate::decoding::StreamingDecoder)'s
3088 /// `read_to_end` fast path; the caller must ensure
3089 /// [`Self::is_at_frame_start`].
3090 ///
3091 /// # Errors
3092 ///
3093 /// Propagates any [`FrameDecoderError`] from block decode, content-size
3094 /// mismatch, or (in `Verify` mode) checksum validation.
3095 pub(crate) fn decode_current_frame_to_vec(
3096 &mut self,
3097 mut input: &[u8],
3098 output: &mut Vec<u8>,
3099 keep_dictionary: bool,
3100 ) -> Result<usize, FrameDecoderError> {
3101 let start_len = output.len();
3102 // The current frame is already initialised (its header consumed by the
3103 // caller, WITH the dictionary applied if the decoder was constructed
3104 // with one). Decode it, then decode any FOLLOWING concatenated /
3105 // skippable frames in `input` so the whole source is consumed to EOF
3106 // and nothing is dropped (matching `read_to_end` semantics).
3107 self.decode_one_frame_to_vec(&mut input, output)?;
3108 self.decode_concatenated_frames_to_vec(&mut input, output, keep_dictionary)?;
3109 Ok(output.len() - start_len)
3110 }
3111
3112 /// Initialise and decode every frame remaining in `input` (concatenated /
3113 /// skippable), APPENDING to `output`. `input` is advanced as frames are
3114 /// consumed; on return it is empty. With `keep_dictionary` each following
3115 /// frame is initialised with the dictionary the decoder holds
3116 /// ([`Self::reset_with_active_dict`]), so a forced dictionary is preserved
3117 /// even for frames that omit the dictionary id (plain [`Self::init`] would
3118 /// resolve dictionaries by id only). Backs the `read_to_end` fast path (the
3119 /// frames after the current one) and its mid-frame fallback (the frames
3120 /// after the partially-read one).
3121 pub(crate) fn decode_concatenated_frames_to_vec(
3122 &mut self,
3123 input: &mut &[u8],
3124 output: &mut Vec<u8>,
3125 keep_dictionary: bool,
3126 ) -> Result<usize, FrameDecoderError> {
3127 let start_len = output.len();
3128 while !input.is_empty() {
3129 let init_result = if keep_dictionary {
3130 self.reset_with_active_dict(&mut *input)
3131 } else {
3132 self.init(&mut *input)
3133 };
3134 match init_result {
3135 Ok(_) => {}
3136 Err(FrameDecoderError::ReadFrameHeaderError(
3137 crate::decoding::errors::ReadFrameHeaderError::SkipFrame { length, .. },
3138 )) => {
3139 *input = input
3140 .get(length as usize..)
3141 .ok_or(FrameDecoderError::FailedToSkipFrame)?;
3142 continue;
3143 }
3144 Err(e) => return Err(e),
3145 }
3146 self.decode_one_frame_to_vec(&mut *input, output)?;
3147 }
3148 Ok(output.len() - start_len)
3149 }
3150
3151 /// Decode the single CURRENT (already-initialised) frame, APPENDING to
3152 /// `output`. Helper for [`Self::decode_current_frame_to_vec`].
3153 fn decode_one_frame_to_vec(
3154 &mut self,
3155 input: &mut &[u8],
3156 output: &mut Vec<u8>,
3157 ) -> Result<usize, FrameDecoderError> {
3158 let frame_start = output.len();
3159 let (content_size, fcs_declared) = {
3160 let s = self.state.as_ref().expect("frame is initialised");
3161 (
3162 s.frame_header.frame_content_size(),
3163 s.frame_header.fcs_declared(),
3164 )
3165 };
3166 // Direct path: a declared, non-empty content size that FITS in `usize`
3167 // (and whose end offset does not overflow). `usize::try_from` guards the
3168 // 32-bit / oversized-FCS truncation; an unrepresentable size falls
3169 // through to the window-bounded ring drain rather than allocating a
3170 // truncated buffer that would violate `run_direct_decode`'s precondition.
3171 //
3172 // Plausibility gate: the direct path `resize`s `output` to the declared
3173 // size up front, so a tiny/truncated frame declaring a huge (but
3174 // representable) FCS would allocate + zero that whole size before the
3175 // body is validated. zstd's per-block ceiling is MAX_BLOCK_SIZE from as
3176 // little as ~4 input bytes, so the declared size cannot legitimately
3177 // exceed `input.len() * (MAX_BLOCK_SIZE / 4)`. Anything larger falls
3178 // through to the ring drain, which grows only as real bytes are produced
3179 // and errors out cheaply on truncated input. `input` spans the remaining
3180 // source (this frame plus any following ones), so the bound only ever
3181 // over-permits — a legitimate frame is never forced off the direct path.
3182 // saturating_mul is intentional: an overflow means the available input
3183 // is so large that any representable FCS is plausible (cap = "no limit").
3184 const MAX_DECOMPRESSION_RATIO: usize = (crate::common::MAX_BLOCK_SIZE / 4) as usize;
3185 if content_size > 0
3186 && let Ok(cs) = usize::try_from(content_size)
3187 && cs <= input.len().saturating_mul(MAX_DECOMPRESSION_RATIO)
3188 && let Some(frame_end) = frame_start.checked_add(cs)
3189 {
3190 // Reserve exactly the frame's content and decode straight into it
3191 // (single copy, no ring). The direct path writes precisely
3192 // `content_size` bytes (erroring otherwise), so the grown region is
3193 // fully written.
3194 output.resize(frame_end, 0);
3195 // On error, drop the just-grown (zeroed) tail before propagating so
3196 // callers never observe bytes that were never decoded.
3197 let written = match self.run_direct_decode(
3198 &mut *input,
3199 &mut output[frame_start..],
3200 Some(content_size),
3201 ) {
3202 Ok(n) => n,
3203 Err(e) => {
3204 output.truncate(frame_start);
3205 return Err(e);
3206 }
3207 };
3208 output.truncate(frame_start + written);
3209 #[cfg(feature = "hash")]
3210 self.verify_content_checksum()?;
3211 return Ok(written);
3212 }
3213 // The ring-drain fallback below pre-reserves `useful_window_size()`
3214 // (= `window.min(FCS)`), which for a single-segment frame is the
3215 // declared FCS itself — so a truncated single-segment frame lying about
3216 // its size would still allocate the pledged window before the body
3217 // errors, sidestepping the direct-path gate above. Reject such a frame
3218 // up front when its declared (FCS-bearing) window exceeds what the
3219 // available input could plausibly produce. Frames without a declared
3220 // size keep their window-descriptor reservation (already capped at
3221 // `MAXIMUM_ALLOWED_WINDOW_SIZE` at init); a small-window multi-segment
3222 // frame still falls through to the ring drain, which errors cheaply on
3223 // the truncated body.
3224 if fcs_declared
3225 && let Some(state) = self.state.as_ref()
3226 && state.useful_window_size() > input.len().saturating_mul(MAX_DECOMPRESSION_RATIO)
3227 {
3228 return Err(FrameDecoderError::FrameContentSizeMismatch {
3229 declared: content_size,
3230 produced: 0,
3231 });
3232 }
3233 // No declared size, explicit FCS=0, or an unrepresentable FCS: window-
3234 // bounded ring drain, appended directly to `output` via
3235 // `collect_to_writer` (no staging buffer).
3236 loop {
3237 self.decode_blocks(&mut *input, BlockDecodingStrategy::UptoBytes(1024 * 1024))?;
3238 self.collect_to_writer(&mut *output)
3239 .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
3240 if self.is_finished() {
3241 // Final flush of the retained window tail.
3242 self.collect_to_writer(&mut *output)
3243 .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
3244 break;
3245 }
3246 }
3247 let produced = (output.len() - frame_start) as u64;
3248 // A declared content size MUST match what the body produced — otherwise
3249 // accept the same corrupt frames `decode_all_impl` rejects (e.g. an
3250 // explicit FCS=0 whose body emits bytes). Use `fcs_declared()` so an
3251 // on-wire FCS=0 is validated, while an unknown size is not.
3252 if fcs_declared && produced != content_size {
3253 return Err(FrameDecoderError::FrameContentSizeMismatch {
3254 declared: content_size,
3255 produced,
3256 });
3257 }
3258 #[cfg(feature = "hash")]
3259 self.verify_content_checksum()?;
3260 Ok(produced as usize)
3261 }
3262
3263 /// Default-feature decode_all_impl: no visitor parameter so the
3264 /// no-lsm build's call surface and codegen are byte-identical to
3265 /// the pre-#172 implementation. Compiles only when `lsm` is OFF.
3266 #[cfg(not(feature = "lsm"))]
3267 fn decode_all_impl(
3268 &mut self,
3269 mut input: &[u8],
3270 mut output: &mut [u8],
3271 mut init_frame: impl FnMut(&mut Self, &mut &[u8]) -> Result<(), FrameDecoderError>,
3272 ) -> Result<usize, FrameDecoderError> {
3273 let mut total_bytes_written = 0;
3274 while !input.is_empty() {
3275 match init_frame(self, &mut input) {
3276 Ok(_) => {}
3277 Err(FrameDecoderError::ReadFrameHeaderError(
3278 crate::decoding::errors::ReadFrameHeaderError::SkipFrame { length, .. },
3279 )) => {
3280 input = input
3281 .get(length as usize..)
3282 .ok_or(FrameDecoderError::FailedToSkipFrame)?;
3283 continue;
3284 }
3285 Err(e) => return Err(e),
3286 };
3287 // Per-frame direct-path dispatch. Now safe to route the
3288 // public `decode_all` here because
3289 // `UserSliceBackend::exec_sequence_inline` returns
3290 // `Result<(), ExecuteSequencesError>` instead of
3291 // panicking on capacity overflow; the error propagates
3292 // up as `FrameDecoderError`. Eligibility (FCS > 0,
3293 // remaining `output` slice holds the declared content)
3294 // puts the frame on the fast path that bypasses the
3295 // FlatBuf/Ring -> `read()` drain copy. Ineligible frames
3296 // (no FCS, output too small) fall through to the legacy
3297 // `decode_blocks` + `read` drain loop below. Dictionary
3298 // frames are eligible: `run_direct_decode` hands the
3299 // shared dict handle to its buffer, and beyond-prefix
3300 // offsets resolve through `repeat_from_dict`.
3301 let (content_size, fcs_declared) = {
3302 let state_ref = self.state.as_ref().expect("init populated state");
3303 (
3304 state_ref.frame_header.frame_content_size(),
3305 state_ref.frame_header.fcs_declared(),
3306 )
3307 };
3308 // Direct decode requires only that the caller slice holds the
3309 // declared content; the inline sequence-exec path no longer
3310 // needs `WILDCOPY_OVERLENGTH` trailing slack because the
3311 // trailing sequence(s) take the bounded (non-overshooting)
3312 // copy in `UserSliceBackend::exec_sequence_bounded`. This is
3313 // the universal "decode into an FCS-sized buffer" case (a
3314 // caller sizing `output` to exactly `frame_content_size`),
3315 // so dropping the slack requirement halves its peak alloc.
3316 //
3317 // Per-block checksums collected inside `run_direct_decode`
3318 // post-loop (over recorded (start, end) ranges of `output`)
3319 // so the direct path stays eligible AND keeps the
3320 // window-size cap (`drop_to_window_size`) between blocks
3321 // that the spec relies on for `offset <= window_size`
3322 // validation. Path choice no longer alters checksum
3323 // semantics.
3324 // A frame that declares no size decodes straight into the
3325 // caller's slice too, the slice being its limit, as upstream
3326 // `ZSTD_decompressDCtx` decodes into `dst`. The drain path
3327 // reserved the frame's whole declared window for it, which for a
3328 // streamed producer's small frame is megabytes for kilobytes.
3329 let declared_size = fcs_declared.then_some(content_size);
3330 let direct_eligible = match declared_size {
3331 Some(declared) => declared > 0 && (output.len() as u64) >= declared,
3332 None => true,
3333 };
3334 if direct_eligible {
3335 let written = self.run_direct_decode(&mut input, output, declared_size)?;
3336 output = &mut output[written..];
3337 total_bytes_written += written;
3338 // Per-frame content-checksum verification (no-op unless the
3339 // mode is `Verify` and the frame carries a checksum).
3340 #[cfg(feature = "hash")]
3341 self.verify_content_checksum()?;
3342 continue;
3343 }
3344 // Non-direct fallback: pre-reserve the backing buffer to
3345 // `window_size` in a single allocation before block decode
3346 // starts, so multi-segment frames don't pay repeated
3347 // `reserve_amortized` grow steps as blocks accumulate (each
3348 // block only reserves MAX_BLOCK_SIZE = 128 KiB, so a window
3349 // > 128 KiB otherwise grows through several intermediate
3350 // sizes with `alloc_zeroed + memcpy` each time).
3351 if let Some(state) = self.state.as_mut() {
3352 // FCS-capped via `decoding_buffer_size` — the same cap
3353 // `decode_blocks` applies, so its per-iteration reserve in
3354 // the loop below cannot grow the buffer back to the raw
3355 // frame window.
3356 state.reserve_decoding_buffer();
3357 }
3358 let frame_start_total = total_bytes_written;
3359 loop {
3360 self.decode_blocks(&mut input, BlockDecodingStrategy::UptoBytes(1024 * 1024))?;
3361 let bytes_written = self
3362 .read(output)
3363 .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
3364 output = &mut output[bytes_written..];
3365 total_bytes_written += bytes_written;
3366 if self.can_collect() != 0 {
3367 return Err(FrameDecoderError::TargetTooSmall);
3368 }
3369 if self.is_finished() {
3370 break;
3371 }
3372 }
3373 // Per-frame FCS validation on the legacy fallback path.
3374 // Use `fcs_declared()` (NOT `content_size > 0`) so an
3375 // empty frame with explicit FCS=0 on the wire still gets
3376 // validated.
3377 if fcs_declared {
3378 let produced = (total_bytes_written - frame_start_total) as u64;
3379 if produced != content_size {
3380 return Err(FrameDecoderError::FrameContentSizeMismatch {
3381 declared: content_size,
3382 produced,
3383 });
3384 }
3385 }
3386 // Per-frame content-checksum verification on the drain path: the
3387 // frame is fully decoded and drained here (is_finished + nothing
3388 // left to collect), so the running digest and stored value are
3389 // final. No-op unless the mode is `Verify`.
3390 #[cfg(feature = "hash")]
3391 self.verify_content_checksum()?;
3392 }
3393
3394 Ok(total_bytes_written)
3395 }
3396
3397 /// `lsm`-feature decode_all_impl: adds the optional skippable
3398 /// visitor parameter consumed by
3399 /// [`Self::decode_all_with_skippable_visitor`]. Mirrors the no-lsm
3400 /// variant including the direct-path dispatch + FCS-validation
3401 /// rationale comments, so the two functions stay in sync; the only
3402 /// behavioral difference is the SkipFrame arm, which uses
3403 /// `split_at(length)` (single bounds check) instead of two
3404 /// separate `get(..length)` / `get(length..)` slices and invokes
3405 /// the visitor (when `Some`) on the borrowed payload before
3406 /// advancing past it.
3407 #[cfg(feature = "lsm")]
3408 #[allow(clippy::type_complexity)]
3409 fn decode_all_impl(
3410 &mut self,
3411 mut input: &[u8],
3412 mut output: &mut [u8],
3413 mut init_frame: impl FnMut(&mut Self, &mut &[u8]) -> Result<(), FrameDecoderError>,
3414 mut skippable_visitor: Option<&mut dyn FnMut(u8, &[u8])>,
3415 ) -> Result<usize, FrameDecoderError> {
3416 let mut total_bytes_written = 0;
3417 while !input.is_empty() {
3418 match init_frame(self, &mut input) {
3419 Ok(_) => {}
3420 Err(FrameDecoderError::ReadFrameHeaderError(
3421 crate::decoding::errors::ReadFrameHeaderError::SkipFrame {
3422 magic_number,
3423 length,
3424 },
3425 )) => {
3426 let length = length as usize;
3427 // Visitor sees the payload slice BEFORE we advance
3428 // past it. Borrowed slice — no allocation. The
3429 // variant is the low nibble of the magic number
3430 // (RFC 8878 §3.1.2). `read_frame_header` only emits
3431 // SkipFrame for magic in 0x184D2A50..=0x184D2A5F, so
3432 // the subtraction fits in 0..=15.
3433 if input.len() < length {
3434 return Err(FrameDecoderError::FailedToSkipFrame);
3435 }
3436 let (payload, rest) = input.split_at(length);
3437 if let Some(visitor) = skippable_visitor.as_mut() {
3438 let variant = (magic_number - 0x184D2A50) as u8;
3439 visitor(variant, payload);
3440 }
3441 input = rest;
3442 continue;
3443 }
3444 Err(e) => return Err(e),
3445 };
3446 // Per-frame direct-path dispatch. Now safe to route the
3447 // public `decode_all` here because
3448 // `UserSliceBackend::exec_sequence_inline` returns
3449 // `Result<(), ExecuteSequencesError>` instead of
3450 // panicking on capacity overflow; the error propagates
3451 // up as `FrameDecoderError`. Eligibility (FCS > 0,
3452 // remaining `output` slice holds the declared content)
3453 // puts the frame on the fast path that bypasses the
3454 // FlatBuf/Ring -> `read()` drain copy. Ineligible frames
3455 // (no FCS, output too small) fall through to the legacy
3456 // `decode_blocks` + `read` drain loop below. Dictionary
3457 // frames are eligible (see the no-lsm path above).
3458 let (content_size, fcs_declared) = {
3459 let state_ref = self.state.as_ref().expect("init populated state");
3460 (
3461 state_ref.frame_header.frame_content_size(),
3462 state_ref.frame_header.fcs_declared(),
3463 )
3464 };
3465 // Only `cap >= frame_content_size` needed; the trailing
3466 // sequence(s) take the bounded copy in
3467 // `UserSliceBackend::exec_sequence_bounded`, so no
3468 // `WILDCOPY_OVERLENGTH` trailing slack is required (see the
3469 // no-lsm path above).
3470 // A frame that declares no size decodes straight into the
3471 // caller's slice too, the slice being its limit, as upstream
3472 // `ZSTD_decompressDCtx` decodes into `dst`. The drain path
3473 // reserved the frame's whole declared window for it, which for a
3474 // streamed producer's small frame is megabytes for kilobytes.
3475 let declared_size = fcs_declared.then_some(content_size);
3476 let direct_eligible = match declared_size {
3477 Some(declared) => declared > 0 && (output.len() as u64) >= declared,
3478 None => true,
3479 };
3480 if direct_eligible {
3481 let written = self.run_direct_decode(&mut input, output, declared_size)?;
3482 output = &mut output[written..];
3483 total_bytes_written += written;
3484 // Per-frame content-checksum verification (no-op unless the
3485 // mode is `Verify` and the frame carries a checksum).
3486 #[cfg(feature = "hash")]
3487 self.verify_content_checksum()?;
3488 continue;
3489 }
3490 // Non-direct fallback: pre-reserve the backing buffer to
3491 // `window_size` once so the per-block growth cycle is
3492 // skipped (see same comment on the no-lsm path above).
3493 if let Some(state) = self.state.as_mut() {
3494 // FCS-capped via `decoding_buffer_size` — the same cap
3495 // `decode_blocks` applies, so its per-iteration reserve in
3496 // the loop below cannot grow the buffer back to the raw
3497 // frame window.
3498 state.reserve_decoding_buffer();
3499 }
3500 let frame_start_total = total_bytes_written;
3501 loop {
3502 self.decode_blocks(&mut input, BlockDecodingStrategy::UptoBytes(1024 * 1024))?;
3503 let bytes_written = self
3504 .read(output)
3505 .map_err(FrameDecoderError::FailedToDrainDecodebuffer)?;
3506 output = &mut output[bytes_written..];
3507 total_bytes_written += bytes_written;
3508 if self.can_collect() != 0 {
3509 return Err(FrameDecoderError::TargetTooSmall);
3510 }
3511 if self.is_finished() {
3512 break;
3513 }
3514 }
3515 // Per-frame FCS validation on the legacy fallback path.
3516 // Use `fcs_declared()` (NOT `content_size > 0`) so an
3517 // empty frame with explicit FCS=0 on the wire still gets
3518 // validated.
3519 if fcs_declared {
3520 let produced = (total_bytes_written - frame_start_total) as u64;
3521 if produced != content_size {
3522 return Err(FrameDecoderError::FrameContentSizeMismatch {
3523 declared: content_size,
3524 produced,
3525 });
3526 }
3527 }
3528 // Per-frame content-checksum verification on the drain path: the
3529 // frame is fully decoded and drained here (is_finished + nothing
3530 // left to collect), so the running digest and stored value are
3531 // final. No-op unless the mode is `Verify`.
3532 #[cfg(feature = "hash")]
3533 self.verify_content_checksum()?;
3534 }
3535
3536 Ok(total_bytes_written)
3537 }
3538
3539 /// Decode multiple frames into the output slice using a serialized dictionary.
3540 ///
3541 /// # Warning
3542 ///
3543 /// Each decoded frame is initialized with the parsed dictionary, even when a
3544 /// frame header omits the optional dictionary ID. Callers must only use this
3545 /// API when they already know the input frames were encoded with that
3546 /// dictionary; otherwise decoded output can be silently corrupted.
3547 pub fn decode_all_with_dict_bytes(
3548 &mut self,
3549 input: &[u8],
3550 output: &mut [u8],
3551 raw_dictionary: &[u8],
3552 ) -> Result<usize, FrameDecoderError> {
3553 let dict = DictionaryHandle::decode_dict(raw_dictionary)?;
3554 self.decode_all_with_dict_handle(input, output, &dict)
3555 }
3556
3557 /// Decode multiple frames into the extra capacity of the output vector.
3558 ///
3559 /// `input` must contain an exact number of frames.
3560 ///
3561 /// `output` must have enough spare capacity to hold the decompressed
3562 /// data. This adds no extra slack: exact-fit output is now eligible
3563 /// for the direct decode path, so a `Vec::with_capacity(fcs)` is
3564 /// decoded straight into without a growth/reallocation. It will NOT
3565 /// grow the vector to fit the decompressed payload itself; the
3566 /// caller's pre-allocated capacity must already cover the data. If
3567 /// you don't know how large the output will be, use
3568 /// [`FrameDecoder::decode_blocks`] instead.
3569 ///
3570 /// This calls [`FrameDecoder::init`], and all bytes currently in the decoder will be lost.
3571 ///
3572 /// The length of the output vector is updated to include the
3573 /// decompressed data. The length is not changed if an error occurs.
3574 pub fn decode_all_to_vec(
3575 &mut self,
3576 input: &[u8],
3577 output: &mut Vec<u8>,
3578 ) -> Result<(), FrameDecoderError> {
3579 let len = output.len();
3580 let cap = output.capacity();
3581 output.resize(cap, 0);
3582 match self.decode_all(input, &mut output[len..]) {
3583 Ok(bytes_written) => {
3584 let new_len = core::cmp::min(len + bytes_written, cap); // Sanitizes `bytes_written`.
3585 output.resize(new_len, 0);
3586 Ok(())
3587 }
3588 Err(e) => {
3589 output.resize(len, 0);
3590 Err(e)
3591 }
3592 }
3593 }
3594
3595 /// Single-frame direct-decode path. Decodes one zstd frame into
3596 /// `output[..content_size]` via a stack-local
3597 /// `DecodeBuffer<UserSliceBackend>`, bypassing the per-block
3598 /// FlatBuf/Ring -> `read()` drain copy.
3599 ///
3600 /// # Preconditions (caller-enforced)
3601 ///
3602 /// - `self.init` (or `init_with_dict_handle`) was called for
3603 /// this frame so `self.state` is populated.
3604 /// - `declared_size` is the frame's declared content size, `> 0`, with
3605 /// `output.len() >= declared_size` (the eligibility gate), or `None`
3606 /// for a frame that declares none. Then `output` itself is the limit,
3607 /// as upstream `ZSTD_decompressDCtx` decodes into `dst`, and a frame
3608 /// that does not fit is `TargetTooSmall` rather than a size mismatch.
3609 /// No `WILDCOPY_OVERLENGTH` trailing slack is required: the trailing
3610 /// sequence(s) take the bounded (non-overshooting) copy in
3611 /// [`UserSliceBackend::exec_sequence_bounded`](crate::decoding::user_slice_buf::UserSliceBackend::exec_sequence_bounded).
3612 ///
3613 /// Dictionary frames are supported: the scratch buffer's shared
3614 /// dict handle is forwarded to the stack-local `DecodeBuffer`, so
3615 /// offsets reaching past the frame's own output resolve through
3616 /// `repeat_from_dict` (the ext-dict slow path).
3617 ///
3618 /// On return, `input` points at the byte immediately after the
3619 /// frame's checksum (or after the last block, when the frame
3620 /// has `content_checksum_flag = 0`). `self.state.frame_finished`
3621 /// is set so [`Self::is_finished`] reports `true`.
3622 fn run_direct_decode(
3623 &mut self,
3624 input: &mut &[u8],
3625 output: &mut [u8],
3626 declared_size: Option<u64>,
3627 ) -> Result<usize, FrameDecoderError> {
3628 #[cfg(test)]
3629 {
3630 self.direct_frames += 1;
3631 }
3632 use super::block_decoder;
3633 use super::decode_buffer::DecodeBuffer;
3634 use super::scratch::DirectScratch;
3635 use super::user_slice_buf::UserSliceBackend;
3636 use crate::io::Read;
3637 use FrameDecoderError as err;
3638
3639 // The most the frame may write: its declared size, or the caller's
3640 // slice for a frame that declares none.
3641 let limit = declared_size.unwrap_or(output.len() as u64);
3642 // Output past `limit`: the frame lied about its size, or it does not
3643 // fit the caller's slice.
3644 let overflow = |produced: u64| match declared_size {
3645 Some(declared) => err::FrameContentSizeMismatch { declared, produced },
3646 None => err::TargetTooSmall,
3647 };
3648
3649 let kernel = self.kernel;
3650 let state = self
3651 .state
3652 .as_mut()
3653 .expect("caller ensures init populated state");
3654
3655 // Fast path: a frame that is a single RAW block spanning the whole
3656 // declared content. Upstream zstd handles this as one `ZSTD_copyRawBlock`
3657 // (a `memmove`) inside `ZSTD_decompressFrame`; do the same here — a direct
3658 // `copy_from_slice` into the caller's output slice — skipping the
3659 // `DirectScratch` / `DecodeBuffer` / `UserSliceBackend` wrapper
3660 // construction and the general per-block loop. Incompressible payloads
3661 // (random / already-compressed data) emit exactly this shape, so the win
3662 // lands on small high-entropy frames where the per-frame machinery, not
3663 // the 1-block copy, dominates.
3664 {
3665 let mut probe = *input;
3666 let mut header_dec = block_decoder::with_kernel(kernel);
3667 if let Ok((bh, hsize)) = header_dec.read_block_header(&mut probe) {
3668 let n = bh.decompressed_size as usize;
3669 // A frame that declares no size takes the shortcut too: the
3670 // slice is its limit, and holding the block means holding the
3671 // frame. Without this the probe parsed the header that the
3672 // general loop below parses again, on the very path (a small
3673 // frame from a streamed producer) this decode is for. The
3674 // block maximum is checked here as the general path checks it:
3675 // a block past it is malformed, and the shortcut must not be
3676 // the way around that.
3677 let window = state.frame_header.window_size().unwrap_or(0) as usize;
3678 if bh.last_block
3679 && matches!(bh.block_type, crate::blocks::block::BlockType::Raw)
3680 && declared_size.is_none_or(|declared| declared == n as u64)
3681 && n <= block_decoder::block_maximum(window)
3682 && probe.len() >= n
3683 && output.len() >= n
3684 {
3685 output[..n].copy_from_slice(&probe[..n]);
3686 *input = &probe[n..];
3687 state.bytes_read_counter += u64::from(hsize) + n as u64;
3688 state.block_counter += 1;
3689 // Consume the trailing 4-byte content checksum UNCONDITIONALLY
3690 // when the frame declares one — exactly like the general
3691 // direct loop and `decode_blocks`. Only the hash SEEDING is
3692 // `hash`-gated; the byte consumption / counter / `check_sum`
3693 // must not be, or a no-`hash` build leaves the 4 bytes in
3694 // `*input` (misparsed as the next frame) and never sets
3695 // `check_sum` (so `is_finished` stays false).
3696 if state.frame_header.descriptor.content_checksum_flag() {
3697 let mut chksum = [0u8; 4];
3698 Read::read_exact(input, &mut chksum).map_err(err::FailedToReadChecksum)?;
3699 state.bytes_read_counter += 4;
3700 state.check_sum = Some(u32::from_le_bytes(chksum));
3701 // Mirror the general path: seed the scratch hash so
3702 // `verify_content_checksum` / `get_calculated_checksum`
3703 // read the digest. Skipped under `ContentChecksum::None`.
3704 #[cfg(feature = "hash")]
3705 if self.content_checksum != ContentChecksum::None {
3706 use core::hash::Hasher;
3707 let mut h = twox_hash::XxHash64::with_seed(0);
3708 h.write(&output[..n]);
3709 match &mut state.decoder_scratch {
3710 DecoderScratchKind::Flat(s) => s.buffer.set_hash(h),
3711 DecoderScratchKind::Ring(s) => s.buffer.set_hash(h),
3712 }
3713 }
3714 }
3715 #[cfg(all(feature = "lsm", feature = "hash"))]
3716 if self.per_block_checksums_enabled {
3717 use core::hash::Hasher;
3718 let mut h = twox_hash::XxHash64::with_seed(0);
3719 h.write(&output[..n]);
3720 self.computed_block_checksums.push(h.finish() as u32);
3721 }
3722 state.decoder_scratch.set_total_output(n as u64);
3723 state.frame_finished = true;
3724 return Ok(n);
3725 }
3726 }
3727 }
3728
3729 // Borrow persistent fields out of whichever scratch variant
3730 // `init` produced (Flat for single_segment, Ring for
3731 // multi-segment) — both expose the same HUF/FSE/Vec
3732 // fields; only `buffer` differs and we don't use that here.
3733 // Macro-style binding avoids the closure / generic
3734 // gymnastics of returning multiple `&mut` from a match arm.
3735 // Resolve the dictionary borrow for this frame BEFORE taking the
3736 // `&mut` field borrows below — `active_dict` is a disjoint field, so
3737 // the shared borrow coexists with the mutable scratch borrows. It is
3738 // threaded as a call-scoped argument into every `Dict`-sourced read
3739 // (the direct path's `repeat_from_dict` ext-dict slow path), mirroring
3740 // C's per-frame pointer hand-off with zero refcount churn.
3741 // Only expose the held dictionary while THIS frame is dict-backed
3742 // (`using_dict` is set per dict-apply, cleared on reset). A reused
3743 // decoder keeps `active_dict` across a no-dict frame for the
3744 // `ptr::eq` reuse-skip, so it must be gated here or a stray
3745 // out-of-window offset on a dictless frame would resolve against the
3746 // stale dictionary content instead of erroring.
3747 let dict_ref = if state.using_dict.is_some() {
3748 state.active_dict.as_ref().map(|h| h.as_dict())
3749 } else {
3750 None
3751 };
3752 let (huf, fse, offset_hist, literals_buffer, block_content_buffer, window_size) =
3753 match &mut state.decoder_scratch {
3754 DecoderScratchKind::Flat(s) => (
3755 &mut s.huf,
3756 &mut s.fse,
3757 &mut s.offset_hist,
3758 &mut s.literals_buffer,
3759 &mut s.block_content_buffer,
3760 s.buffer.window_size,
3761 ),
3762 DecoderScratchKind::Ring(s) => (
3763 &mut s.huf,
3764 &mut s.fse,
3765 &mut s.offset_hist,
3766 &mut s.literals_buffer,
3767 &mut s.block_content_buffer,
3768 s.buffer.window_size,
3769 ),
3770 };
3771 let backend = UserSliceBackend::from_slice(output);
3772 let buffer = DecodeBuffer::from_backend(backend, window_size);
3773 let mut direct = DirectScratch {
3774 huf,
3775 fse,
3776 offset_hist,
3777 literals_buffer,
3778 block_content_buffer,
3779 buffer,
3780 };
3781
3782 // Block loop. Mirrors `decode_blocks` (without the
3783 // strategy-bounded early exit — we always decode the whole
3784 // frame in one shot for the direct path). Keeps
3785 // `state.bytes_read_counter` / `state.block_counter` in
3786 // sync with `decode_blocks` so post-call accessors
3787 // (`bytes_read_from_source`, `blocks_decoded`) return
3788 // accurate values.
3789 let mut block_dec = block_decoder::with_kernel(kernel);
3790 // Track total output bytes against the declared
3791 // `frame_content_size` via the buffer's actual write
3792 // counter — `BlockHeader.decompressed_size` is 0 for
3793 // Compressed blocks (the header parser can't know the
3794 // expanded size before decoding the body), so per-header
3795 // tracking would always count 0 for those blocks and
3796 // miscount frames that aren't pure Raw/RLE.
3797 let mut produced: u64 = 0;
3798 // Per-block output ranges captured during the direct-path
3799 // loop. After the loop we re-borrow `output` (post-drop of
3800 // `direct`) and XXH64 each range into
3801 // `self.computed_block_checksums`, so the digests vector
3802 // stays consistent with the legacy `decode_blocks` path
3803 // regardless of which dispatch the frame took.
3804 // `Vec::new()` does not allocate, so this stays free when
3805 // `per_block_checksums_enabled` is false: the `push` and the
3806 // post-loop hashing loop are both gated by the same flag.
3807 #[cfg(all(feature = "lsm", feature = "hash"))]
3808 let mut block_ranges: alloc::vec::Vec<(usize, usize)> = alloc::vec::Vec::new();
3809 // Frame-level XXH64, accumulated PER BLOCK right after each block
3810 // decodes — the bytes are still cache-resident then. The previous
3811 // shape hashed the whole output once after the loop, which re-read
3812 // the entire frame cold: a full extra memory pass that the
3813 // reference implementation does not make (it hashes incrementally
3814 // per block). Invisible on outputs that fit L3, ~1.14x wall on a
3815 // 100 MiB all-raw decode and the dominant CI gap on
3816 // bandwidth-limited hosts.
3817 #[cfg(feature = "hash")]
3818 let mut running_hash: Option<twox_hash::XxHash64> =
3819 if state.frame_header.descriptor.content_checksum_flag()
3820 && self.content_checksum != ContentChecksum::None
3821 {
3822 Some(twox_hash::XxHash64::with_seed(0))
3823 } else {
3824 None
3825 };
3826 loop {
3827 #[cfg(all(feature = "lsm", feature = "hash"))]
3828 let produced_before: Option<usize> = if self.per_block_checksums_enabled {
3829 Some(produced as usize)
3830 } else {
3831 None
3832 };
3833 // Failing-block coordinates captured before the header read (see
3834 // the `decode_blocks` loop for the rationale).
3835 let block_index = state.block_counter as u32;
3836 let block_frame_offset = state.bytes_read_counter as u32;
3837 let (block_header, hsize) =
3838 block_dec.read_block_header(&mut *input).map_err(|source| {
3839 block_header_decode_error(source, block_index, block_frame_offset)
3840 })?;
3841 state.bytes_read_counter += u64::from(hsize);
3842 // Pre-flight FCS check ONLY for Raw / RLE blocks where
3843 // `decompressed_size` is the actual block output size.
3844 // For Compressed blocks the header field is 0; the
3845 // post-decode check below catches overflow via the
3846 // backend's actual write counter delta.
3847 let block_upper = u64::from(block_header.decompressed_size);
3848 if block_upper > 0 && produced + block_upper > limit {
3849 // Raw/RLE block headers claim more output than the FCS
3850 // allows (a corrupt frame) or the caller's slice holds.
3851 return Err(overflow(produced + block_upper));
3852 }
3853 // Slice-source fast path: consume the block body
3854 // straight from `input` without copying into the
3855 // persistent `block_content_buffer`.
3856 let body_consumed = match block_dec.decode_block_content_from_slice(
3857 &block_header,
3858 &mut direct,
3859 dict_ref,
3860 &mut *input,
3861 ) {
3862 Ok(n) => n,
3863 // Defense-in-depth: RLE / Raw block whose declared
3864 // `decompressed_size` slipped past the per-block
3865 // pre-flight above and tripped the backend's
3866 // fallible write surface.
3867 Err(crate::decoding::errors::DecodeBlockContentError::BackendOverflow {
3868 ..
3869 }) => {
3870 // Use saturating_add on the
3871 // `produced + decompressed_size` sum. Each block
3872 // is bounded by 128 KiB (MAX_BLOCK_SIZE), but
3873 // accumulated `produced` can grow toward
3874 // u64::MAX across adversarial frames. Saturating
3875 // avoids a panic on the error path itself.
3876 return Err(overflow(
3877 produced.saturating_add(u64::from(block_header.decompressed_size)),
3878 ));
3879 }
3880 // Compressed-block in-block overshoot: the sequence
3881 // executor (upstream zstd-inline path) or the match-repeat
3882 // fallback tripped the fixed-capacity backend's per-write
3883 // check. Unlike Raw/RLE, a Compressed block carries no
3884 // header-declared output size, so `produced` is computed
3885 // from the partial fill: `tail` bytes were written before
3886 // the failing op, and `requested` is what overflowed —
3887 // their sum is a strict lower bound on the frame's true
3888 // expanded size and is always > `limit`. With a declared
3889 // size the slice holds at least that much, so any overflow
3890 // means the frame exceeded its FCS, never a caller-undersized
3891 // buffer, and folds into the same `FrameContentSizeMismatch`
3892 // contract as Raw/RLE; without one the slice is the limit.
3893 // An overflow that stays within `limit` was refused by the
3894 // per-block output ceiling instead: a malformed block, which
3895 // takes the generic arm below.
3896 Err(crate::decoding::errors::DecodeBlockContentError::DecompressBlockError(
3897 crate::decoding::errors::DecompressBlockError::ExecuteSequencesError(ref e),
3898 )) if e.output_overflow_requested().is_some_and(|requested| {
3899 (direct.buffer.buffer_ref().tail() as u64).saturating_add(requested as u64)
3900 > limit
3901 }) =>
3902 {
3903 let requested = e
3904 .output_overflow_requested()
3905 .expect("guard guarantees Some") as u64;
3906 let tail = direct.buffer.buffer_ref().tail() as u64;
3907 return Err(overflow(tail.saturating_add(requested)));
3908 }
3909 // A no-sequence block's literals did not fit the slice. Every
3910 // direct-path entry holds `output.len() >= limit` (a declared
3911 // size is checked against the slice before the path is chosen,
3912 // and an undeclared frame's limit IS the slice), so a write
3913 // past the slice is a write past `limit`: the frame outgrew its
3914 // declared size, or the caller's target is short.
3915 Err(crate::decoding::errors::DecodeBlockContentError::DecompressBlockError(
3916 crate::decoding::errors::DecompressBlockError::LiteralsOutputOverflow {
3917 tail,
3918 requested,
3919 capacity,
3920 },
3921 )) => {
3922 debug_assert!(
3923 capacity as u64 >= limit,
3924 "direct path entered with a short slice"
3925 );
3926 return Err(overflow((tail as u64).saturating_add(requested as u64)));
3927 }
3928 Err(e) => {
3929 return Err(block_body_decode_error(
3930 e,
3931 block_index,
3932 block_frame_offset,
3933 &block_header,
3934 hsize,
3935 ));
3936 }
3937 };
3938 // Hash this block's freshly-written bytes while they are hot
3939 // (see `running_hash` above). `tail()` is the physical write
3940 // cursor: `drop_to_window_size` below only advances the head,
3941 // so `[prev_tail, tail)` is exactly this block's output.
3942 #[cfg(feature = "hash")]
3943 if let Some(hasher) = running_hash.as_mut() {
3944 use core::hash::Hasher;
3945 hasher.write(direct.buffer.buffer_ref().written_since(produced as usize));
3946 }
3947 produced = direct.buffer.buffer_ref().tail() as u64;
3948 // Post-decode FCS overflow check.
3949 if produced > limit {
3950 return Err(overflow(produced));
3951 }
3952 state.bytes_read_counter += body_consumed;
3953 state.block_counter += 1;
3954 #[cfg(all(feature = "lsm", feature = "hash"))]
3955 if let Some(produced_before) = produced_before {
3956 block_ranges.push((produced_before, produced as usize));
3957 }
3958 // Cap the visible buffer at window_size between blocks
3959 // so the next block's match-offset validation matches
3960 // the spec's `offset <= window_size` rule.
3961 direct.buffer.drop_to_window_size();
3962 if block_header.last_block {
3963 if state.frame_header.descriptor.content_checksum_flag() {
3964 let mut chksum = [0u8; 4];
3965 input
3966 .read_exact(&mut chksum)
3967 .map_err(err::FailedToReadChecksum)?;
3968 state.bytes_read_counter += 4;
3969 state.check_sum = Some(u32::from_le_bytes(chksum));
3970 }
3971 break;
3972 }
3973 }
3974 // Final sanity: blocks summed to exactly the declared size.
3975 if let Some(declared) = declared_size
3976 && produced != declared
3977 {
3978 return Err(err::FrameContentSizeMismatch { declared, produced });
3979 }
3980
3981 let written = produced as usize;
3982 state.decoder_scratch.set_total_output(produced);
3983 state.frame_finished = true;
3984 // `direct`'s last use is in the decode loop above; NLL therefore
3985 // releases its `&mut output` borrow before here, freeing `output` for
3986 // the hash re-borrow below. No explicit `drop(direct)` is needed:
3987 // `DirectScratch` now holds only borrowed dict POINTERS (not an owned
3988 // `Arc`), so it is not a `Drop` type whose glue would hold the borrow
3989 // to end-of-scope.
3990 // Per-block XXH64 (low 32 bits) over the captured ranges.
3991 // Mirrors `decode_blocks`' per-block hashing so the digests
3992 // vector stays identical regardless of which dispatch path
3993 // the frame took. Ranges were recorded inside the loop while
3994 // `direct` held a mutable borrow on `output`; now that the
3995 // borrow is dropped we can read the slices directly.
3996 #[cfg(all(feature = "lsm", feature = "hash"))]
3997 if self.per_block_checksums_enabled {
3998 use core::hash::Hasher;
3999 for (start, end) in &block_ranges {
4000 let mut h = twox_hash::XxHash64::with_seed(0);
4001 h.write(&output[*start..*end]);
4002 self.computed_block_checksums.push(h.finish() as u32);
4003 }
4004 }
4005 #[cfg(feature = "hash")]
4006 if let Some(hasher) = running_hash {
4007 // Propagate the per-block-accumulated hasher state (see the
4008 // `running_hash` rationale above the loop) so the frame-tail
4009 // XXH64 check and `get_calculated_checksum()` read the digest.
4010 // `running_hash` is `None` for flag-off frames or
4011 // `ContentChecksum::None` — nothing to verify there, and
4012 // `get_calculated_checksum()` returns `None`, matching the skip.
4013 match &mut state.decoder_scratch {
4014 DecoderScratchKind::Flat(s) => s.buffer.set_hash(hasher),
4015 DecoderScratchKind::Ring(s) => s.buffer.set_hash(hasher),
4016 }
4017 }
4018 Ok(written)
4019 }
4020}
4021
4022/// Read bytes from the decode_buffer that are no longer needed. While the frame is not yet finished
4023/// this will retain window_size bytes, else it will drain it completely
4024impl Read for FrameDecoder {
4025 fn read(&mut self, target: &mut [u8]) -> Result<usize, Error> {
4026 let state = match &mut self.state {
4027 None => return Ok(0),
4028 Some(s) => s,
4029 };
4030 if state.frame_finished {
4031 state.decoder_scratch.buffer_read_all(target)
4032 } else {
4033 state.decoder_scratch.buffer_read(target)
4034 }
4035 }
4036}
4037
4038#[cfg(test)]
4039mod tests;