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//!
14//! No FFI, no cmake, no system zstd. `no_std` builds are supported by
15//! disabling the default `std` feature.
16//!
17//! # CPU kernel features
18//!
19//! The decode hot paths ship per-CPU-tier SIMD kernels. With `std` the tier
20//! is chosen at runtime (CPU-feature detection, cached on first use); on
21//! `no_std` it is chosen at compile time from `cfg(target_feature)`.
22//! Each tier is gated by a cargo feature, all enabled by default (a universal
23//! binary that picks the best available tier per the above): `kernel_scalar`,
24//! `kernel_sse2`, `kernel_bmi2`, `kernel_avx2`, `kernel_vbmi2` (x86) and
25//! `kernel_neon`, `kernel_sve` (aarch64). The chain mirrors the ISA
26//! dependency (`kernel_avx2` implies `kernel_bmi2` implies `kernel_sse2`;
27//! `kernel_sve` implies `kernel_neon`). The scalar kernel is always compiled,
28//! so any subset is valid; a flag is inert on architectures it doesn't apply
29//! to. Constrained targets can shrink the binary by trimming tiers, e.g.
30//! `--no-default-features --features kernel_scalar` compiles out the per-tier
31//! SIMD kernel dispatch, its BMI2/AVX2/VBMI2/NEON trampolines, and the
32//! explicit SSE2/NEON intrinsics in the small fixed-size copy primitives —
33//! all of which are gated on the matching `kernel_*` feature. The `kernel_*`
34//! features control the crate's own explicit SIMD; they do not constrain the
35//! compiler's autovectorizer, which may still emit vector instructions from
36//! ordinary scalar code regardless of the enabled tiers.
37//!
38//! The packaged README is included below for the docs.rs landing page; the
39//! API anchors above link straight into the per-module documentation.
40//!
41//! [RFC 8878]: https://www.rfc-editor.org/rfc/rfc8878
42// Keep crate docs aligned with the packaged README via the crate-local symlink in `zstd/README.md`.
43#![doc = include_str!("../README.md")]
44#![no_std]
45#![deny(trivial_casts, trivial_numeric_casts, rust_2018_idioms)]
46#![cfg_attr(docsrs, feature(doc_cfg))]
47
48#[cfg(feature = "std")]
49extern crate std;
50
51#[cfg(not(feature = "rustc-dep-of-std"))]
52extern crate alloc;
53
54#[cfg(feature = "std")]
55pub(crate) const VERBOSE: bool = false;
56
57macro_rules! vprintln {
58 ($($x:expr),*) => {
59 #[cfg(feature = "std")]
60 if crate::VERBOSE {
61 std::println!($($x),*);
62 }
63 }
64}
65
66mod bit_io;
67mod common;
68/// Smallest accepted block-size target (the `ZSTD_TARGETCBLOCKSIZE_MIN`
69/// bound): the single source of truth shared by the Rust setters
70/// (`set_target_block_size`) and the C ABI parameter surface.
71pub use common::MIN_TARGET_BLOCK_SIZE;
72mod cpu_kernel;
73pub mod decoding;
74#[cfg(feature = "dict_builder")]
75#[cfg_attr(docsrs, doc(cfg(feature = "dict_builder")))]
76pub mod dictionary;
77pub mod encoding;
78mod histogram;
79
80#[cfg(feature = "lsm")]
81#[cfg_attr(docsrs, doc(cfg(feature = "lsm")))]
82pub mod skippable;
83
84pub(crate) mod blocks;
85
86#[cfg(feature = "fuzz_exports")]
87pub mod fse;
88#[cfg(feature = "fuzz_exports")]
89pub mod huff0;
90
91// `pub fn init_state<K: CpuKernel>` and friends inside the
92// fuzz_exports-public `huff0` module name `crate::cpu_kernel::CpuKernel`
93// in their signatures. Without a publicly-reachable path to `CpuKernel`
94// the bound triggers `private_bounds` / `private_interfaces`. Re-export
95// under the same feature gate so the fuzz harness build is clean.
96#[cfg(feature = "fuzz_exports")]
97pub use crate::cpu_kernel::{CpuKernel, ScalarKernel};
98
99/// Name of the active CPU kernel tier (entropy / sequence hot paths) for this
100/// process — for diagnostics and benchmark/dashboard reporting. See
101/// [`cpu_kernel::active_cpu_kernel_name`].
102pub use crate::cpu_kernel::active_cpu_kernel_name;
103
104#[cfg(not(feature = "fuzz_exports"))]
105pub(crate) mod fse;
106#[cfg(not(feature = "fuzz_exports"))]
107pub(crate) mod huff0;
108
109#[cfg(feature = "std")]
110pub mod io_std;
111
112#[cfg(feature = "std")]
113pub use io_std as io;
114
115#[cfg(not(feature = "std"))]
116pub mod io_nostd;
117
118#[cfg(not(feature = "std"))]
119pub use io_nostd as io;
120
121#[cfg(test)]
122mod tests;
123
124/// Re-exports of internal types used by benchmarks.
125///
126/// Gated behind the `bench_internals` feature so normal builds do not
127/// widen the public API surface. Not part of the stable API; items may
128/// change or disappear without notice.
129#[cfg(feature = "bench_internals")]
130#[doc(hidden)]
131pub mod testing {
132 pub use crate::bit_io::BitReaderReversed;
133 // `BitReaderReversed` is generic over `K: CpuKernel = ScalarKernel`,
134 // so both the trait bound and the default need a `pub` path to
135 // match the re-exported type's visibility. Without this the
136 // bench-build trips `private_bounds` / `private_interfaces`.
137 pub use crate::cpu_kernel::{CpuKernel, ScalarKernel};
138
139 /// Bench-only facade for the decoder wildcopy implementation.
140 ///
141 /// # Safety
142 /// Caller must satisfy the same safety contract as
143 /// `decoding::copy_bytes_overshooting_for_bench`.
144 #[inline(always)]
145 pub unsafe fn copy_bytes_overshooting_for_bench(
146 src: (*const u8, usize),
147 dst: (*mut u8, usize),
148 copy_at_least: usize,
149 ) {
150 // Keep decoder internals crate-private and expose only this bench shim.
151 unsafe { crate::decoding::copy_bytes_overshooting_for_bench(src, dst, copy_at_least) };
152 }
153
154 /// Maximum block size per RFC 8878 §3.1.1.2.3 (128 KiB).
155 /// Exposed for parity tests that feed exactly-one-block chunks
156 /// into the donor splitter comparator.
157 pub const MAX_BLOCK_SIZE: u32 = crate::common::MAX_BLOCK_SIZE;
158
159 /// Run our donor-port block splitter on a 128 KB chunk.
160 ///
161 /// `split_level` mirrors donor `ZSTD_splitBlock(level)`: `0` selects
162 /// the borders heuristic (`ZSTD_splitBlock_fromBorders`), `1..=4`
163 /// select `ZSTD_splitBlock_byChunks` at the corresponding sampling
164 /// level. Returns the split position (or `block.len()` if no split).
165 ///
166 /// Crate-internal facade for the donor-parity comparator test —
167 /// the underlying functions stay `fn` so they don't widen the
168 /// stable API surface.
169 pub fn block_splitter_decision(block: &[u8], split_level: usize) -> usize {
170 crate::encoding::frame_compressor::block_splitter_decision_for_bench(block, split_level)
171 }
172}
173
174/// SIMD wildcopy overshoot slack carried by every decoder backend
175/// (currently **32 bytes**). Sized so the AVX2 chunked kernel in
176/// `simd_copy::copy_bytes_overshooting` (32-byte stride on x86-64) can
177/// fire on tail copies near the end of a fixed-capacity output buffer.
178/// Donor zstd's `WILDCOPY_OVERLENGTH` is also 32 bytes today; this
179/// matches that contract.
180///
181/// Public so callers sizing an output slice for
182/// [`crate::decoding::FrameDecoder::decode_all`] can size
183/// `frame_content_size + WILDCOPY_OVERLENGTH` symbolically without
184/// duplicating the value. Use the const reference rather than a
185/// hardcoded literal — `simd_copy::copy_bytes_overshooting` already
186/// ships an AVX-512 64-byte chunked kernel, and the slack may grow
187/// further to reliably enable that wider kernel at buffer tails
188/// (mirroring how the bump from 16 → 32 enabled the AVX2 32-byte
189/// kernel at the tail).
190pub const WILDCOPY_OVERLENGTH: usize = crate::decoding::buffer_backend::WILDCOPY_OVERLENGTH;