structured_zstd/decoding/mod.rs
1//! RFC 8878 Zstandard decoder.
2//!
3//! The entry points:
4//!
5//! * [`StreamingDecoder`] — implements [`crate::io::Read`] over a compressed
6//! byte stream, transparently parsing the frame header and concatenated
7//! frames. The typical choice for application code.
8//! * [`FrameDecoder`] — single-frame interface; use when the caller manages
9//! the input buffer manually (zero-copy slices, network framing, etc).
10//! * `workspace::WorkspaceDecoder` (feature `caller-workspace`): streaming
11//! decoder over a byte slice the caller sizes and owns, with no allocation
12//! and limits on window, output and work. For consumers that account their
13//! memory themselves, such as browser bundles verifying a download.
14//! * [`DictionaryHandle`] — pre-parsed dictionary handle. Parse the
15//! dictionary bytes once with [`DictionaryHandle::decode_dict`] and reuse
16//! the handle across every subsequent decode; saves the per-frame
17//! dictionary parse cost when the same dictionary is used many times in a
18//! row.
19//!
20//! Both decoders expose dictionary-aware constructors / methods,
21//! though the exact naming differs:
22//!
23//! * [`StreamingDecoder::new_with_dictionary_handle`] /
24//! [`StreamingDecoder::new_with_dictionary_bytes`]
25//! * [`FrameDecoder::decode_all_with_dict_handle`] /
26//! [`FrameDecoder::decode_all_with_dict_bytes`]
27//!
28//! The `_handle` variants reuse a previously parsed
29//! [`DictionaryHandle`]; the `_bytes` variants parse the dictionary
30//! per call (suitable for one-off decodes).
31//!
32//! Errors surface through [`errors::FrameDecoderError`] and the per-decoder
33//! error types in the [`errors`] submodule.
34
35pub mod errors;
36mod frame_decoder;
37mod streaming_decoder;
38#[cfg(feature = "caller-workspace")]
39#[cfg_attr(docsrs, doc(cfg(feature = "caller-workspace")))]
40pub mod workspace;
41
42pub use dictionary::{Dictionary, DictionaryHandle, MAGIC_NUM as DICTIONARY_MAGIC};
43pub use frame_decoder::{BlockDecodingStrategy, ContentChecksum, FrameDecoder};
44
45/// Largest window a frame may declare before a decoder that holds the window
46/// itself refuses it, unless [`FrameDecoder::set_max_window_size`] raised the
47/// ceiling.
48///
49/// The bound is what makes decoding untrusted input safe: a frame header can
50/// ask for a window far larger than the data behind it, and honouring that
51/// would let a few bytes of input demand gigabytes of memory.
52pub use crate::common::MAXIMUM_ALLOWED_WINDOW_SIZE;
53
54/// Largest window any decode accepts, the ceiling
55/// [`FrameDecoder::set_max_window_size`] can be raised to.
56pub use crate::common::MAX_DECODER_WINDOW_SIZE;
57#[cfg(feature = "lsm")]
58pub use frame_decoder::{PartialDecode, ResumeInput, ResumeState};
59pub use streaming_decoder::{DictionaryRefused, FinishedFrame, StreamingDecoder};
60
61/// Decompressed size a frame declares in its header, as read by
62/// [`read_frame_content_size`] without decoding the frame body.
63#[derive(Copy, Clone, Debug, PartialEq, Eq)]
64pub enum FrameContentSize {
65 /// The header carried an explicit `Frame_Content_Size` field (in bytes).
66 Known(u64),
67 /// The header did not declare a content size; the true size is only
68 /// known after decoding (or from out-of-band knowledge).
69 Unknown,
70}
71
72/// Read the decompressed size a frame declares in its header, without
73/// decoding the frame body.
74///
75/// Parses only the leading frame header of `src`. Returns
76/// [`FrameContentSize::Known`] when the header carries an explicit
77/// `Frame_Content_Size`, or [`FrameContentSize::Unknown`] when it does not.
78/// This backs the C `ZSTD_getFrameContentSize` entry point, where the two
79/// variants map to a concrete size and `ZSTD_CONTENTSIZE_UNKNOWN`.
80///
81/// # Errors
82/// Returns [`ReadFrameHeaderError`](errors::ReadFrameHeaderError) when `src`
83/// is too short to hold a header, carries a bad magic number, or begins with
84/// a skippable frame.
85///
86/// ```rust
87/// use structured_zstd::encoding::{compress_slice_to_vec, CompressionLevel};
88/// use structured_zstd::decoding::{read_frame_content_size, FrameContentSize};
89/// let frame = compress_slice_to_vec(&[42u8; 100], CompressionLevel::Default);
90/// assert_eq!(read_frame_content_size(&frame).unwrap(), FrameContentSize::Known(100));
91/// ```
92pub fn read_frame_content_size(
93 src: &[u8],
94) -> Result<FrameContentSize, errors::ReadFrameHeaderError> {
95 let (header, _consumed) = frame::read_frame_header_with_format(src, false)?;
96 Ok(if header.fcs_declared() {
97 FrameContentSize::Known(header.frame_content_size())
98 } else {
99 FrameContentSize::Unknown
100 })
101}
102
103/// Error from [`find_frame_compressed_size`].
104#[derive(Debug)]
105pub enum FrameSizeError {
106 /// The frame header could not be parsed.
107 Header(errors::ReadFrameHeaderError),
108 /// The buffer ends before the frame's blocks (or trailing checksum) are
109 /// complete.
110 Truncated,
111 /// A block declared the reserved block type, which is invalid per RFC 8878.
112 ReservedBlock,
113 /// A block declared a `Block_Size` larger than the frame's
114 /// `Block_Maximum_Size` (`min(Window_Size, 128 KiB)`), which is invalid per
115 /// RFC 8878 §3.1.1.2. Accepting it would let a corrupt frame pass a size
116 /// query and make the no-`Frame_Content_Size` decompressed-bound
117 /// under-count (each block can regenerate at most `Block_Maximum_Size`).
118 OversizedBlock,
119}
120
121/// On-disk byte length of the FIRST frame in `src` — magic number, frame
122/// header, every block, and the trailing content checksum when present —
123/// computed by walking the block headers without decoding any block body.
124///
125/// For a skippable frame, returns its full `8 + Frame_Size` length. This backs
126/// the C `ZSTD_findFrameCompressedSize` entry point; the returned value is the
127/// offset at which a following concatenated frame would begin.
128///
129/// # Errors
130/// [`FrameSizeError`] when the header is unreadable, the buffer is truncated
131/// mid-frame, or a block uses the reserved type.
132///
133/// ```rust
134/// use structured_zstd::encoding::{compress_slice_to_vec, CompressionLevel};
135/// use structured_zstd::decoding::find_frame_compressed_size;
136/// let frame = compress_slice_to_vec(&[5u8; 256], CompressionLevel::Default);
137/// assert_eq!(find_frame_compressed_size(&frame).unwrap(), frame.len());
138/// ```
139pub fn find_frame_compressed_size(src: &[u8]) -> Result<usize, FrameSizeError> {
140 let (header, header_len) = match frame::read_frame_header_with_format(src, false) {
141 Ok(parsed) => parsed,
142 // Skippable frame: magic (4) + Frame_Size field (4) + payload.
143 Err(errors::ReadFrameHeaderError::SkipFrame { length, .. }) => {
144 return 8usize
145 .checked_add(length as usize)
146 .filter(|end| *end <= src.len())
147 .ok_or(FrameSizeError::Truncated);
148 }
149 Err(e) => return Err(FrameSizeError::Header(e)),
150 };
151
152 let walk = walk_blocks(src, header_len as usize, frame_block_size_max(&header))?;
153 if header.descriptor.content_checksum_flag() {
154 walk.end
155 .checked_add(4)
156 .filter(|end| *end <= src.len())
157 .ok_or(FrameSizeError::Truncated)
158 } else {
159 Ok(walk.end)
160 }
161}
162
163/// Result of walking the block sequence of one frame (between the header and
164/// the optional trailing checksum).
165struct BlockWalk {
166 /// Offset just past the last block (before any content checksum).
167 end: usize,
168 /// Number of blocks in the frame.
169 count: u64,
170}
171
172/// `Block_Maximum_Size` for the frame: `min(Window_Size, 128 KiB)`. Per RFC
173/// 8878 §3.1.1.2 every block's `Block_Size` is bounded by this, and each block
174/// regenerates at most this many bytes. Single-segment frames omit the
175/// `Window_Descriptor`; their window equals the declared content size.
176fn frame_block_size_max(header: &frame::FrameHeader) -> usize {
177 let window_size = match header.window_descriptor() {
178 Some(desc) => {
179 let exponent = u64::from(desc >> 3);
180 let mantissa = u64::from(desc & 0x7);
181 let window_base = 1u64 << (10 + exponent);
182 window_base + (window_base / 8) * mantissa
183 }
184 None => header.frame_content_size(),
185 };
186 // The 128 KiB cap keeps the result within usize on every target.
187 window_size.min(128 * 1024) as usize
188}
189
190/// Walk the block headers of a single frame starting at `start` (the offset of
191/// the first block header), validating each fits in `src` and declares a
192/// `Block_Size` no larger than `max_block_size` (the frame's
193/// `Block_Maximum_Size`). Does not consume the trailing content checksum.
194/// Shared by [`find_frame_compressed_size`] and [`frame_decompressed_bound`] so
195/// the on-disk-size and block-count views never diverge.
196fn walk_blocks(
197 src: &[u8],
198 start: usize,
199 max_block_size: usize,
200) -> Result<BlockWalk, FrameSizeError> {
201 let mut offset = start;
202 let mut count = 0u64;
203 loop {
204 // 3-byte block header (RFC 8878 §3.1.1.2): bit0 last-block flag,
205 // bits1-2 block type, bits3-23 Block_Size.
206 let hdr = src
207 .get(offset..offset + 3)
208 .ok_or(FrameSizeError::Truncated)?;
209 let raw = u32::from(hdr[0]) | (u32::from(hdr[1]) << 8) | (u32::from(hdr[2]) << 16);
210 let last_block = (raw & 1) != 0;
211 let block_type = (raw >> 1) & 0b11;
212 let block_size = (raw >> 3) as usize;
213 // On-disk bytes following the header: RLE stores a single byte
214 // regardless of the run length; Raw/Compressed store Block_Size bytes;
215 // the reserved type is invalid.
216 let on_disk = match block_type {
217 1 => 1, // RLE
218 0 | 2 => block_size, // Raw / Compressed
219 _ => return Err(FrameSizeError::ReservedBlock),
220 };
221 // RFC 8878 §3.1.1.2: Block_Size MUST NOT exceed Block_Maximum_Size for
222 // any block type (it bounds both the on-disk Raw/Compressed payload and
223 // the RLE/Raw regenerated size). Reject rather than accept a corrupt
224 // declaration that would otherwise pass the size query and let the
225 // no-FCS bound under-count.
226 if block_size > max_block_size {
227 return Err(FrameSizeError::OversizedBlock);
228 }
229 offset = offset
230 .checked_add(3 + on_disk)
231 .filter(|end| *end <= src.len())
232 .ok_or(FrameSizeError::Truncated)?;
233 count += 1;
234 if last_block {
235 break;
236 }
237 }
238 Ok(BlockWalk { end: offset, count })
239}
240
241/// Upper bound on the decompressed size of the FIRST frame in `src`, without
242/// decoding the body. Backs the C `ZSTD_decompressBound` (per-frame term).
243///
244/// Returns the exact size when the header declares `Frame_Content_Size`;
245/// otherwise a valid (loose) bound of `block_count * block_size_max`, where
246/// `block_size_max = min(window_size, 128 KiB)` — every block decompresses to
247/// at most that many bytes. Skippable frames contribute `0`.
248///
249/// # Errors
250/// [`FrameSizeError`] on an unreadable header, truncation, or a reserved block.
251pub fn frame_decompressed_bound(src: &[u8]) -> Result<u64, FrameSizeError> {
252 let (header, header_len) = match frame::read_frame_header_with_format(src, false) {
253 Ok(parsed) => parsed,
254 // Skippable frame contributes 0, but its full payload must be present:
255 // truncation is an error per this function's contract.
256 Err(errors::ReadFrameHeaderError::SkipFrame { length, .. }) => {
257 return 8usize
258 .checked_add(length as usize)
259 .filter(|end| *end <= src.len())
260 .map(|_| 0)
261 .ok_or(FrameSizeError::Truncated);
262 }
263 Err(e) => return Err(FrameSizeError::Header(e)),
264 };
265
266 // Walk the blocks (and the optional checksum trailer) so a truncated frame
267 // is rejected even when Frame_Content_Size is declared — without this the
268 // declared-FCS path would return a bound for an incomplete buffer. The
269 // per-frame block maximum both bounds the walk and scales the no-FCS bound.
270 let block_size_max = frame_block_size_max(&header);
271 let walk = walk_blocks(src, header_len as usize, block_size_max)?;
272 if header.descriptor.content_checksum_flag() {
273 walk.end
274 .checked_add(4)
275 .filter(|end| *end <= src.len())
276 .ok_or(FrameSizeError::Truncated)?;
277 }
278
279 if header.fcs_declared() {
280 return Ok(header.frame_content_size());
281 }
282 // Saturating is intentional here: this is an UPPER bound, so capping at the
283 // maximum representable value is the correct ceiling for a pathologically
284 // large frame, not a masked arithmetic bug. Each of `walk.count` blocks
285 // regenerates at most `block_size_max` bytes (now enforced by `walk_blocks`,
286 // so the bound can no longer be undercut by an oversized block header).
287 Ok(walk.count.saturating_mul(block_size_max as u64))
288}
289
290/// Frame header fields decoded by [`read_frame_header_info`], mirroring the
291/// values the C `ZSTD_getFrameHeader` fills into a `ZSTD_FrameHeader`.
292#[derive(Copy, Clone, Debug)]
293pub struct FrameHeaderInfo {
294 /// Declared decompressed size, or [`FrameContentSize::Unknown`] when the
295 /// header omits the `Frame_Content_Size` field.
296 pub content_size: FrameContentSize,
297 /// Decoder window size in bytes (the minimum buffer needed to decode the
298 /// frame). For single-segment frames this equals the content size.
299 pub window_size: u64,
300 /// Dictionary id required to decode the frame, if the header carries one.
301 pub dictionary_id: Option<u32>,
302 /// Whether a 32-bit content checksum trails the frame.
303 pub content_checksum: bool,
304 /// Header length in bytes, measured in the parsed input format: it includes
305 /// the 4-byte magic number in the default format, but excludes it when
306 /// parsed as magicless (`read_frame_header_info(.., true)`), since those 4
307 /// bytes are not present on the wire in that mode.
308 pub header_size: usize,
309}
310
311/// Length in bytes of the frame header at the start of `src`, including the
312/// 4-byte magic number (the offset at which the first block begins). Backs the
313/// C `ZSTD_frameHeaderSize`.
314///
315/// Only the magic number and the descriptor byte are needed: the length
316/// follows from the descriptor alone, so a caller holding just that five-byte
317/// prefix learns how much of the header is still to read. Upstream's
318/// `ZSTD_frameHeaderSize` measures it the same way
319/// (`zstd_decompress.c:416-429`), without looking at the descriptor's other
320/// bits, so a header this library refuses to decode is still measured.
321///
322/// # Errors
323/// [`ReadFrameHeaderError`](errors::ReadFrameHeaderError) when `src` is shorter
324/// than five bytes, has a bad magic number, or is a skippable frame.
325///
326/// ```rust
327/// use structured_zstd::decoding::frame_header_size;
328/// // Magic number and a descriptor announcing a window byte only.
329/// assert_eq!(frame_header_size(&[0x28, 0xB5, 0x2F, 0xFD, 0x00]).unwrap(), 6);
330/// ```
331pub fn frame_header_size(src: &[u8]) -> Result<usize, errors::ReadFrameHeaderError> {
332 frame::measure_header_from_slice(src)
333}
334
335/// Decode the leading frame header fields of `src` without decoding the body.
336///
337/// Backs the C `ZSTD_getFrameHeader`. When `magicless` is `true` the 4-byte
338/// magic prefix is assumed absent (the `ZSTD_f_zstd1_magicless` format); the
339/// caller must know out-of-band that the stream is magicless. The reported
340/// [`FrameHeaderInfo::window_size`] is the raw value derived from the header
341/// (no maximum-window policy applied here; that bound is enforced at decode
342/// time), so callers see the frame's own declared window even when it exceeds
343/// a decoder limit.
344///
345/// # Errors
346/// As [`read_frame_content_size`].
347///
348/// ```rust
349/// use structured_zstd::encoding::{compress_slice_to_vec, CompressionLevel};
350/// use structured_zstd::decoding::{read_frame_header_info, FrameContentSize};
351/// let frame = compress_slice_to_vec(&[7u8; 512], CompressionLevel::Default);
352/// let info = read_frame_header_info(&frame, false).unwrap();
353/// assert_eq!(info.content_size, FrameContentSize::Known(512));
354/// assert!(info.window_size >= 512);
355/// ```
356pub fn read_frame_header_info(
357 src: &[u8],
358 magicless: bool,
359) -> Result<FrameHeaderInfo, errors::ReadFrameHeaderError> {
360 let (header, consumed) = frame::read_frame_header_with_format(src, magicless)?;
361 let content_size = if header.fcs_declared() {
362 FrameContentSize::Known(header.frame_content_size())
363 } else {
364 FrameContentSize::Unknown
365 };
366 // Compute the window size without the decode-time maximum-window check
367 // (RFC 8878 §3.1.1.1.2). `window_descriptor()` returns `None` for a
368 // single-segment frame, where the window equals the content size.
369 let window_size = match header.window_descriptor() {
370 Some(desc) => {
371 let exponent = u64::from(desc >> 3);
372 let mantissa = u64::from(desc & 0x7);
373 let window_base = 1u64 << (10 + exponent);
374 window_base + (window_base / 8) * mantissa
375 }
376 None => header.frame_content_size(),
377 };
378 Ok(FrameHeaderInfo {
379 content_size,
380 window_size,
381 dictionary_id: header.dictionary_id(),
382 content_checksum: header.descriptor.content_checksum_flag(),
383 header_size: consumed as usize,
384 })
385}
386
387pub(crate) mod block_decoder;
388pub(crate) mod buffer_backend;
389pub(crate) mod decode_buffer;
390pub(crate) mod dictionary;
391pub(crate) mod exec_sequence_inline;
392// FlatBuf is the compile-time-monomorphised "frame fits in window"
393// backend selected via `DecodeBuffer<FlatBuf>`. `FrameDecoder`'s
394// `DecoderScratchKind` picks it when the frame header has
395// `Single_Segment_flag` set; the ring backend remains the default
396// for multi-segment frames. See backlog item #132 for the wiring
397// rationale.
398pub(crate) mod flat_buf;
399pub(crate) mod frame;
400pub(crate) mod literals_section_decoder;
401pub(crate) mod prefetch;
402mod ringbuffer;
403#[allow(dead_code)]
404pub(crate) mod scratch;
405// Per-kernel monolithic sequence-section decoder entry points. Each
406// kernel has its own self-contained function with the full pipeline
407// (outer init, both arms, decode_one, execute_one) inlined inside one
408// `#[target_feature]`-scoped body. The dispatcher in
409// `sequence_section_decoder::decode_and_execute_sequences` selects the
410// kernel ONCE per call via cached `detect_cpu_kernel`. aarch64 Neon
411// and Sve still go through the K-generic
412// `decode_and_execute_sequences_impl` shared body until their own
413// monoliths land.
414//
415// The shared helpers (`decode_and_execute_sequences_impl`,
416// `run_pipelined_sequence_loop`, `decode_one_sequence_inline`, the
417// `execute_one_sequence_pipelined*` wrappers) live on aarch64
418// (Neon/Sve dispatch arms in `decode_and_execute_sequences`) and in
419// tests, but are orphan on x86_64 production builds where the
420// per-kernel monoliths bypass them entirely. Each carries
421// `#[allow(dead_code)]` so the `-D warnings` clippy gate stays green
422// on x86_64 without losing the cross-arch reuse. The vestigial
423// `_bmi2`/`_avx2`/`_vbmi2` variants are pre-R12 macro-dispatch
424// helpers with no remaining callers; they should be cleaned up in
425// a follow-up PR once the per-kernel monolithic shape is fully
426// settled.
427#[cfg(all(target_arch = "x86_64", feature = "kernel-avx2"))]
428pub(crate) mod seq_decoder_avx2;
429#[cfg(all(target_arch = "x86_64", feature = "kernel-bmi2"))]
430pub(crate) mod seq_decoder_bmi2;
431pub(crate) mod seq_decoder_scalar;
432#[cfg(all(target_arch = "x86_64", feature = "kernel-vbmi2"))]
433pub(crate) mod seq_decoder_vbmi2;
434pub(crate) mod sequence_execution;
435pub(crate) mod sequence_section_decoder;
436pub(crate) mod simd_copy;
437/// Diagnostic-only re-export of the copy-shape histogram counters. Public
438/// only when the `copy-shape-stats` feature is on (off in shipping builds).
439#[cfg(feature = "copy-shape-stats")]
440pub use simd_copy::shape_stats;
441// `UserSliceBackend` is the compile-time-monomorphised backend that
442// writes directly into the caller's `&mut [u8]` output slice, used
443// by the `FrameDecoder::decode_all` direct-decode path. It
444// eliminates the `FlatBuf` drain copy + anonymous-page-fault cost
445// on large literal sections. Wiring happens via
446// `DecodeBuffer<UserSliceBackend<'a>>`; the lifetime binds the
447// backend to the caller's slice for the call duration.
448pub(crate) mod user_slice_buf;
449
450#[cfg(feature = "bench-internals")]
451pub(crate) use self::simd_copy::copy_bytes_overshooting_for_bench;
452
453#[cfg(test)]
454mod frame_inspection_tests;