Skip to main content

structured_zstd/
lib.rs

1//! Pure-Rust Zstandard codec with a production-grade decoder, dictionary
2//! handle reuse, and an actively-improved encoder.
3//!
4//! The crate ships:
5//!
6//! * [`decoding`] — [RFC 8878] decoder ([`decoding::StreamingDecoder`],
7//!   [`decoding::FrameDecoder`], dictionary-backed paths via
8//!   [`decoding::DictionaryHandle`]).
9//! * [`encoding`] — frame compressor, streaming encoder, named and numeric
10//!   compression levels ([`encoding::CompressionLevel`]).
11//! * [`dictionary`] (feature `dict-builder`) — COVER / FastCOVER training
12//!   plus raw-to-finalized dictionary helpers.
13//! * `decoding::workspace` (feature `caller-workspace`): streaming decoder
14//!   that runs entirely in caller-owned memory, never allocating, with
15//!   caller-set limits on window, output and work.
16//!
17//! No FFI, no cmake, no system zstd. `no_std` builds are supported by
18//! disabling the default `std` feature.
19//!
20//! # CPU kernel features
21//!
22//! Both the decode and the encode hot paths ship per-CPU-tier SIMD kernels.
23//! On x86 and aarch64 with `std` the tier is chosen at runtime (CPU-feature
24//! detection, cached on first use); on `no_std` it is chosen at compile time
25//! from `cfg(target_feature)`. WebAssembly is compile-time only either way:
26//! its kernels additionally require `target_feature = "simd128"`, so a wasm
27//! build without `-C target-feature=+simd128` stays scalar.
28//!
29//! Each tier is gated by a cargo feature: `kernel-scalar`, `kernel-sse`,
30//! `kernel-bmi2`, `kernel-avx2`, `kernel-vbmi2` (x86) and `kernel-neon`,
31//! `kernel-sve` (aarch64). All are on by default except `kernel-vbmi2`, which
32//! is opt-in because the AVX-512 decode tier measures slower than AVX2 on the
33//! bursty decode path, so the default build is a universal binary that picks
34//! the best available tier per the above. `kernel-scalar` gates no code: the
35//! scalar path is the mandatory fallback and is always compiled, so the flag
36//! exists only to name that tier explicitly in a feature set. `kernel-vbmi2`
37//! and `kernel-sve` are decoder-only; the encoder has no AVX-512 or SVE tier.
38//! The chain mirrors the ISA
39//! dependency (`kernel-avx2` implies `kernel-bmi2` implies `kernel-sse`;
40//! `kernel-sve` implies `kernel-neon`). `kernel-sse` covers two x86 tiers:
41//! SSE4.2 where the CPU has it, and a plain-SSE2 tier otherwise, so a
42//! pre-SSE4.2 CPU still gets vector match compares. Any subset is valid, and a
43//! flag is inert on architectures it doesn't apply to. Constrained targets can
44//! shrink the binary by trimming
45//! tiers: `--no-default-features --features kernel-scalar` compiles out every
46//! per-tier dispatch, the BMI2/AVX2/VBMI2/NEON trampolines, and the explicit
47//! SSE2/NEON intrinsics in both the copy primitives and the encoder
48//! match-finder. The `kernel_*` features control the crate's own explicit
49//! SIMD; they do not constrain the compiler's autovectorizer, which may still
50//! emit vector instructions from ordinary scalar code regardless of the
51//! enabled tiers.
52//!
53//! The packaged README is included below for the docs.rs landing page; the
54//! API anchors above link straight into the per-module documentation.
55//!
56//! [RFC 8878]: https://www.rfc-editor.org/rfc/rfc8878
57// Keep crate docs aligned with the packaged README via the crate-local symlink in `zstd/README.md`.
58#![doc = include_str!("../README.md")]
59#![no_std]
60#![deny(trivial_casts, trivial_numeric_casts, rust_2018_idioms)]
61#![cfg_attr(docsrs, feature(doc_cfg))]
62
63#[cfg(feature = "std")]
64extern crate std;
65
66#[cfg(not(feature = "rustc-dep-of-std"))]
67extern crate alloc;
68
69#[cfg(feature = "std")]
70pub(crate) const VERBOSE: bool = false;
71
72macro_rules! vprintln {
73    ($($x:expr),*) => {
74        #[cfg(feature = "std")]
75        if crate::VERBOSE {
76            std::println!($($x),*);
77        }
78    }
79}
80
81mod bit_io;
82mod common;
83/// Largest block the format allows (RFC 8878 3.1.1.2.3, 128 KiB): the single
84/// source of truth for every surface that has to name it, the C ABI included.
85/// A frame's own maximum is the smaller of this and its window.
86pub use common::MAX_BLOCK_SIZE;
87/// Smallest accepted maximum block size (the `ZSTD_BLOCKSIZE_MAX_MIN` bound),
88/// shared by `set_max_block_size` and the C ABI parameter surface.
89pub use common::MIN_MAX_BLOCK_SIZE;
90/// Smallest accepted block-size target (the `ZSTD_TARGETCBLOCKSIZE_MIN`
91/// bound): the single source of truth shared by the Rust setters
92/// (`set_target_block_size`) and the C ABI parameter surface.
93pub use common::MIN_TARGET_BLOCK_SIZE;
94mod cpu_kernel;
95pub mod decoding;
96#[cfg(feature = "dict-builder")]
97#[cfg_attr(docsrs, doc(cfg(feature = "dict-builder")))]
98pub mod dictionary;
99pub mod encoding;
100mod histogram;
101
102pub mod skippable;
103
104pub(crate) mod blocks;
105
106#[cfg(feature = "fuzz-exports")]
107pub mod fse;
108#[cfg(feature = "fuzz-exports")]
109pub mod huff0;
110
111// `pub fn init_state<K: CpuKernel>` and friends inside the
112// fuzz-exports-public `huff0` module name `crate::cpu_kernel::CpuKernel`
113// in their signatures. Without a publicly-reachable path to `CpuKernel`
114// the bound triggers `private_bounds` / `private_interfaces`. Re-export
115// under the same feature gate so the fuzz harness build is clean.
116#[cfg(feature = "fuzz-exports")]
117pub use crate::cpu_kernel::{CpuKernel, ScalarKernel};
118
119/// Name of the active CPU kernel tier (entropy / sequence hot paths) for this
120/// process — for diagnostics and benchmark/dashboard reporting. See
121/// [`cpu_kernel::active_cpu_kernel_name`].
122pub use crate::cpu_kernel::active_cpu_kernel_name;
123/// The ceiling on the instruction sets the kernels may use: see
124/// [`set_cpu_ceiling`].
125pub use crate::cpu_kernel::{
126    CpuCeilingError, CpuLevel, UnknownCpuLevel, cpu_ceiling, set_cpu_ceiling,
127};
128/// Name of the match-finder kernel tier for this process. See
129/// [`encoding::active_match_kernel_name`].
130pub use crate::encoding::active_match_kernel_name;
131
132#[cfg(not(feature = "fuzz-exports"))]
133pub(crate) mod fse;
134#[cfg(not(feature = "fuzz-exports"))]
135pub(crate) mod huff0;
136
137#[cfg(feature = "std")]
138pub mod io_std;
139
140#[cfg(feature = "std")]
141pub use io_std as io;
142
143#[cfg(not(feature = "std"))]
144pub mod io_nostd;
145
146#[cfg(not(feature = "std"))]
147pub use io_nostd as io;
148
149#[cfg(test)]
150mod tests;
151
152/// Re-exports of internal types used by benchmarks.
153///
154/// Gated behind the `bench-internals` feature so normal builds do not
155/// widen the public API surface. Not part of the stable API; items may
156/// change or disappear without notice.
157#[cfg(feature = "bench-internals")]
158#[doc(hidden)]
159pub mod testing {
160    /// Compression parameters selected for `(level, srcSize, dictSize)` →
161    /// `(windowLog, chainLog, hashLog, searchLog, minMatch, targetLength,
162    /// strategy)`. Facade for the `ffi-bench` parity test that diffs the
163    /// selection against the reference `ZSTD_getCParams`.
164    pub fn compression_params(
165        level: i32,
166        src: u64,
167        dict: usize,
168    ) -> (u32, u32, u32, u32, u32, u32, u32) {
169        // `ZSTD_getCParams` spells an unknown source size as 0.
170        let cp =
171            crate::encoding::LevelParameters::for_level(level, (src != 0).then_some(src), dict);
172        (
173            cp.window_log,
174            cp.chain_log,
175            cp.hash_log,
176            cp.search_log,
177            cp.min_match,
178            cp.target_length,
179            cp.strategy.ordinal(),
180        )
181    }
182
183    /// Force every HUF table build onto the cheap single-build path (skip the
184    /// #167 table-log search) so a bench harness can A/B the search across
185    /// levels. Measurement-only.
186    pub fn set_force_cheap_huf(on: bool) {
187        crate::huff0::huff0_encoder::set_force_cheap_huf(on);
188    }
189
190    pub use crate::bit_io::BitReaderReversed;
191    // `BitReaderReversed` is generic over `K: CpuKernel = ScalarKernel`,
192    // so both the trait bound and the default need a `pub` path to
193    // match the re-exported type's visibility. Without this the
194    // bench-build trips `private_bounds` / `private_interfaces`.
195    pub use crate::cpu_kernel::{CpuKernel, ScalarKernel};
196
197    /// Bench-only facade for the decoder wildcopy implementation.
198    ///
199    /// # Safety
200    /// Caller must satisfy the same safety contract as
201    /// `decoding::copy_bytes_overshooting_for_bench`.
202    #[inline(always)]
203    pub unsafe fn copy_bytes_overshooting_for_bench(
204        src: (*const u8, usize),
205        dst: (*mut u8, usize),
206        copy_at_least: usize,
207    ) {
208        // Keep decoder internals crate-private and expose only this bench shim.
209        unsafe { crate::decoding::copy_bytes_overshooting_for_bench(src, dst, copy_at_least) };
210    }
211
212    /// Maximum block size per RFC 8878 §3.1.1.2.3 (128 KiB).
213    /// Exposed for parity tests that feed exactly-one-block chunks
214    /// into the block-splitter comparator.
215    pub const MAX_BLOCK_SIZE: u32 = crate::common::MAX_BLOCK_SIZE;
216
217    /// Run our block splitter on a 128 KB chunk.
218    ///
219    /// `split_level` mirrors upstream zstd `ZSTD_splitBlock(level)`: `0` selects
220    /// the borders heuristic (`ZSTD_splitBlock_fromBorders`), `1..=4`
221    /// select `ZSTD_splitBlock_byChunks` at the corresponding sampling
222    /// level. Returns the split position (or `block.len()` if no split).
223    ///
224    /// Crate-internal facade for the block-splitter parity comparator test —
225    /// the underlying functions stay `fn` so they don't widen the
226    /// stable API surface.
227    pub fn block_splitter_decision(block: &[u8], split_level: usize) -> usize {
228        crate::encoding::frame_compressor::block_splitter_decision_for_bench(block, split_level)
229    }
230
231    /// White-box capture of our Huffman weight description for `data`:
232    /// `(description, weights)` where `description` is the length-prefixed
233    /// FSE payload and `weights` the raw per-symbol weights. Facade for the
234    /// `ffi-bench` conformance test that feeds it through the C `HUF_readStats`.
235    pub fn huf_weight_description(data: &[u8]) -> (alloc::vec::Vec<u8>, alloc::vec::Vec<u8>) {
236        crate::huff0::huff0_encoder::huf_weight_description_for_test(data)
237    }
238
239    /// White-box capture of our 4-stream Huffman payload for `data`. Facade for
240    /// the `ffi-bench` conformance test that decodes it through the C HUF reader.
241    pub fn huf_encode4x(data: &[u8]) -> alloc::vec::Vec<u8> {
242        crate::huff0::huff0_encoder::huf_encode4x_for_test(data)
243    }
244
245    /// White-box capture of the level-22 sequence stream (literal-length,
246    /// offset, match-length triples) our match generator emits for `data`.
247    /// Facade for the sequence-conformance test in `ffi-bench`, which
248    /// compares this stream against the C reference's `ZSTD_generateSequences`
249    /// output. Pure Rust; the C side stays out of this crate.
250    pub fn collect_level22_sequences(data: &[u8]) -> alloc::vec::Vec<(usize, usize, usize)> {
251        crate::encoding::match_generator::collect_level22_sequences(data)
252    }
253
254    /// FastCOVER dictionary roundtrip fixture: `(finalized_dictionary,
255    /// compressed_frame, original_payload)`. Facade for the `ffi-bench`
256    /// conformance test that decodes `compressed_frame` against the dictionary
257    /// through the C decoder and compares to `original_payload`.
258    #[cfg(feature = "dict-builder")]
259    pub fn dict_roundtrip_fixture() -> (
260        alloc::vec::Vec<u8>,
261        alloc::vec::Vec<u8>,
262        alloc::vec::Vec<u8>,
263    ) {
264        crate::dictionary::dict_roundtrip_fixture()
265    }
266
267    /// The content the legacy trainer selects, before any header: facade for
268    /// the `ffi-bench` test that compares it with the tail of the reference's
269    /// `ZDICT_trainFromBuffer_legacy` dictionary. `None` when the trainer
270    /// yields nothing.
271    #[cfg(feature = "dict-builder")]
272    pub fn legacy_dict_content(
273        samples: &[u8],
274        sample_sizes: &[usize],
275        dict_size: usize,
276        selectivity: u32,
277    ) -> Option<alloc::vec::Vec<u8>> {
278        crate::dictionary::legacy_dict_content(samples, sample_sizes, dict_size, selectivity)
279    }
280
281    pub use crate::blocks::block::BlockType;
282
283    /// First block's type (raw / rle / compressed) in a frame. Facade over the
284    /// internal block decoder for the FFI parity tests in `ffi-bench`.
285    pub fn first_block_type(frame: &[u8]) -> BlockType {
286        let (_, header_size) = crate::decoding::frame::read_frame_header_with_format(frame, false)
287            .expect("frame header should parse");
288        let mut decoder = crate::decoding::block_decoder::new();
289        let (header, _) = decoder
290            .read_block_header(&frame[header_size as usize..])
291            .expect("block header should parse");
292        header.block_type
293    }
294
295    /// `(single_segment_flag, frame_content_size, fcs_field_size_bytes)` parsed
296    /// from a frame header. Facade for the FFI parity tests in `ffi-bench` so
297    /// they need not reach into the internal `FrameHeader` type.
298    pub fn frame_header_info(frame: &[u8]) -> (bool, u64, u8) {
299        let (h, _) = crate::decoding::frame::read_frame_header_with_format(frame, false)
300            .expect("frame header should parse");
301        (
302            h.descriptor.single_segment_flag(),
303            h.frame_content_size(),
304            h.descriptor.frame_content_size_bytes().unwrap_or(0),
305        )
306    }
307}
308
309/// SIMD wildcopy overshoot slack carried by every decoder backend
310/// (currently **32 bytes**). Sized so the AVX2 chunked kernel in
311/// `simd_copy::copy_bytes_overshooting` (32-byte stride on x86-64) can
312/// fire on tail copies near the end of a fixed-capacity output buffer.
313/// Upstream zstd's `WILDCOPY_OVERLENGTH` is also 32 bytes today; this
314/// matches that contract.
315///
316/// Public so callers sizing an output slice for
317/// [`crate::decoding::FrameDecoder::decode_all`] can size
318/// `frame_content_size + WILDCOPY_OVERLENGTH` symbolically without
319/// duplicating the value. Use the const reference rather than a
320/// hardcoded literal — `simd_copy::copy_bytes_overshooting` already
321/// ships an AVX-512 64-byte chunked kernel, and the slack may grow
322/// further to reliably enable that wider kernel at buffer tails
323/// (mirroring how the bump from 16 → 32 enabled the AVX2 32-byte
324/// kernel at the tail).
325pub const WILDCOPY_OVERLENGTH: usize = crate::decoding::buffer_backend::WILDCOPY_OVERLENGTH;