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