zstd_native/enc/mod.rs
1//! Compression: a port of libzstd 1.6.0's compressor whose output is
2//! byte-identical to libzstd's for the same input and parameters (issue #6).
3//!
4//! Layout (each module ports the named libzstd file; function names in
5//! comments refer to libzstd):
6//! - `bitwriter`: `BIT_CStream_t` (common/bitstream.h)
7//! - `hist`: compress/hist.c
8//! - `fse_enc`: compress/fse_compress.c (+ FSE encoder parts of common/fse.h)
9//! - `huf_enc`: compress/huf_compress.c
10//! - `literals`: compress/zstd_compress_literals.c
11//! - `sequences`: compress/zstd_compress_sequences.c
12//! - `compress`: blocks and frames from compress/zstd_compress.c
13//! - `seq_store`: `SeqStore_t`, `ZSTD_storeSeq`, `ZSTD_count`, hashing
14//! (compress/zstd_compress_internal.h)
15//! - `params`: compression levels and parameter adjustment (clevels.h,
16//! `ZSTD_getCParams_internal`, `ZSTD_adjustCParams_internal`)
17//! - `fast`: compress/zstd_fast.c (noDict, extDict and dictMatchState
18//! variants; the window)
19//! - `dfast`: compress/zstd_double_fast.c (noDict, extDict, dictMatchState)
20//! - `lazy`: compress/zstd_lazy.c (greedy, lazy, lazy2, btlazy2: parser,
21//! hash chain and binary tree; noDict, extDict and dictMatchState)
22//! - `row`: compress/zstd_lazy.c (the row-based match finder)
23//! - `opt`: compress/zstd_opt.c (btopt, btultra, btultra2: price model,
24//! binary tree match finder, optimal parser, dictionary statistics;
25//! noDict, extDict and dictMatchState)
26//! - `presplit`: compress/zstd_preSplit.c
27//! - `split`: the post-block splitter from compress/zstd_compress.c
28//! (`ZSTD_compressBlock_splitBlock`)
29//! - `stream`: streaming compression from compress/zstd_compress.c
30//! (`ZSTD_compressStream2`, `ZSTD_compressStream_generic` in buffered
31//! mode, `ZSTD_CCtx_init_compressStream2`); the input ring buffer makes
32//! the window non-contiguous, which the match finders' extDict variants
33//! handle
34//! - `cdict`: dictionaries (`ZSTD_CDict`, `ZSTD_createCDict`,
35//! `ZSTD_compress_insertDictionary`, `ZSTD_loadCEntropy`,
36//! `ZSTD_loadDictionaryContent`, `ZSTD_resetCCtx_usingCDict`): loading,
37//! CDicts with tagged tables, attaching or copying them, the parameters
38//! with a dictionary
39//! - `ldm`: long distance matching, compress/zstd_ldm.c (gear rolling
40//! hash, long match generation, `ZSTD_ldm_blockCompress`), which libzstd
41//! enables by itself for `btopt` and above with a 128 MiB window; the
42//! optimal parser takes its matches as candidates (`ZSTD_optLdm_*` in
43//! `opt`)
44//! - `mt` (with `std`): multithreaded compression,
45//! compress/zstdmt_compress.c (jobs compressed by worker threads, the
46//! overlap between jobs, the serial LDM step) and how
47//! `ZSTD_compressStream2` drives it with `nbWorkers >= 1`
48//! - `table`: the match finder tables, 64-byte aligned like libzstd's
49//! workspace tables (`ZSTD_cwksp`)
50#![allow(dead_code)] // filled in step by step (issue #6)
51
52pub(crate) mod bitwriter;
53#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
54pub(crate) mod block_asm;
55pub(crate) mod cdict;
56pub(crate) mod compress;
57pub(crate) mod dfast;
58pub(crate) mod fast;
59pub(crate) mod fse_enc;
60pub(crate) mod hist;
61pub(crate) mod huf_enc;
62pub(crate) mod lazy;
63pub(crate) mod ldm;
64pub(crate) mod literals;
65#[cfg(feature = "std")]
66pub(crate) mod mt;
67pub(crate) mod opt;
68pub(crate) mod params;
69pub(crate) mod presplit;
70pub(crate) mod row;
71#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
72pub(crate) mod seq_asm;
73pub(crate) mod seq_store;
74pub(crate) mod sequences;
75pub(crate) mod split;
76pub(crate) mod stream;
77pub(crate) mod table;
78
79pub use cdict::EncoderDictionary;
80use compress::FrameParams;
81pub use compress::compress_bound;
82pub use stream::{CompressProgress, EndOp, StreamEncoder};
83
84/// Compresses `src` into one zstd frame at `level` (1 to 22, negative for
85/// faster; 0 means the default, 3), like libzstd's `ZSTD_compress`: the
86/// output is byte-identical to libzstd 1.6.0's.
87///
88/// Every level and strategy is implemented, `fast` to `btultra2`, with
89/// libzstd's block splitters and its long distance matcher, which it
90/// enables by itself at level 22 for inputs over 64 MiB (a 128 MiB window;
91/// memory use is then libzstd's too, about 700 MiB of tables).
92///
93/// ```
94/// let data = b"hello hello hello hello hello hello";
95/// let compressed = zstd_native::compress(data, 1)?;
96/// assert_eq!(zstd_native::decompress(&compressed)?, data);
97/// # Ok::<(), zstd_native::Error>(())
98/// ```
99///
100/// # Errors
101///
102/// None in practice: the output buffer is [`compress_bound`] bytes, always
103/// enough.
104pub fn compress(src: &[u8], level: i32) -> crate::error::Result<alloc::vec::Vec<u8>> {
105 with_cached(|fc| compress::compress_with(fc, src, level, true, FrameParams::default()))
106}
107
108/// Compresses into `dst`, returning the compressed size; `dst` of
109/// [`compress_bound`]`(src.len())` bytes is always enough.
110///
111/// # Errors
112///
113/// [`Error::OutputTooSmall`](crate::Error::OutputTooSmall) if `dst` is too
114/// small, or as [`compress`].
115pub fn compress_to_slice(src: &[u8], dst: &mut [u8], level: i32) -> crate::error::Result<usize> {
116 with_cached(|fc| {
117 compress::compress_to_slice_with(fc, src, dst, level, true, FrameParams::default())
118 })
119}
120
121/// Compresses `src` into one zstd frame at `level` with the dictionary
122/// `dict` (zstd-format or raw content, see [`EncoderDictionary`]; an empty
123/// one is no dictionary). The output is byte-identical to libzstd 1.6.0's
124/// `ZSTD_CCtx_loadDictionary` then `ZSTD_compress2` on a new context (the
125/// `zstd` crate's `bulk::Compressor::with_dictionary(level, dict)`). It
126/// indexes the dictionary on every call: for many inputs, use a
127/// [`Compressor`] (which indexes it once) or an [`EncoderDictionary`].
128///
129/// ```
130/// let dict = b"the quick brown fox jumps over the lazy dog";
131/// let compressed = zstd_native::compress_with_dictionary(b"the lazy dog jumps", dict, 3)?;
132/// let mut d = zstd_native::Decompressor::with_dictionary(zstd_native::Dictionary::new(dict)?);
133/// assert_eq!(d.decompress(&compressed)?, b"the lazy dog jumps");
134/// # Ok::<(), zstd_native::Error>(())
135/// ```
136///
137/// # Errors
138///
139/// [`Error::InvalidDictionary`](crate::Error::InvalidDictionary) if a
140/// zstd-format dictionary is corrupt, or as [`compress`].
141pub fn compress_with_dictionary(
142 src: &[u8],
143 dict: &[u8],
144 level: i32,
145) -> crate::error::Result<alloc::vec::Vec<u8>> {
146 let mut slot = cdict::DictSlot::local(dict)?;
147 with_cached(|fc| {
148 compress::compress_dict_with(fc, &mut slot, src, level, true, FrameParams::default())
149 })
150}
151
152type Cached = Option<alloc::boxed::Box<compress::FrameCompressor>>;
153
154/// Runs `f` with a per-thread cached compressor (with `std`): reusing its
155/// tables and buffers matters for small inputs, as in libzstd's CCtx.
156#[cfg(feature = "std")]
157fn with_cached<T>(f: impl FnOnce(&mut Cached) -> T) -> T {
158 use core::cell::Cell;
159 std::thread_local! {
160 static CACHED: Cell<Cached> = const { Cell::new(None) };
161 }
162 let mut c = CACHED.with(Cell::take);
163 let r = f(&mut c);
164 CACHED.with(|cell| cell.set(c));
165 r
166}
167
168#[cfg(not(feature = "std"))]
169fn with_cached<T>(f: impl FnOnce(&mut Cached) -> T) -> T {
170 f(&mut None)
171}
172
173/// A reusable compressor (libzstd's `ZSTD_CCtx`): keeps its tables and
174/// buffers between frames, which matters for many small inputs, and
175/// optionally a dictionary.
176///
177/// ```
178/// let mut c = zstd_native::Compressor::new(1);
179/// let a = c.compress(b"first message, first message")?;
180/// let b = c.compress(b"second message")?;
181/// assert_eq!(zstd_native::decompress(&a)?, b"first message, first message");
182/// assert_eq!(zstd_native::decompress(&b)?, b"second message");
183/// # Ok::<(), zstd_native::Error>(())
184/// ```
185///
186/// With a dictionary, its frames are byte-identical to those of libzstd's
187/// context with the dictionary loaded (`ZSTD_CCtx_loadDictionary`, the
188/// `zstd` crate's `bulk::Compressor::with_dictionary`) or referenced
189/// (`ZSTD_CCtx_refCDict`, `with_prepared_dictionary`):
190///
191/// ```
192/// let dict = b"{\"id\": 0, \"name\": \"\", \"tags\": []}";
193/// let mut c = zstd_native::Compressor::with_dictionary(3, dict)?;
194/// let a = c.compress(b"{\"id\": 1, \"name\": \"one\", \"tags\": [\"a\"]}")?;
195/// let mut d = zstd_native::Decompressor::with_dictionary(zstd_native::Dictionary::new(dict)?);
196/// assert_eq!(d.decompress(&a)?, b"{\"id\": 1, \"name\": \"one\", \"tags\": [\"a\"]}");
197/// # Ok::<(), zstd_native::Error>(())
198/// ```
199///
200/// With `std`, it can compress with worker threads
201/// ([`set_workers`](Self::set_workers)), as libzstd's `ZSTD_compress2` with
202/// `ZSTD_c_nbWorkers`.
203pub struct Compressor {
204 level: i32,
205 inner: Cached,
206 dict: cdict::DictSlot,
207 fparams: FrameParams,
208 #[cfg(feature = "std")]
209 mt_params: mt::MtParams,
210 #[cfg(feature = "std")]
211 mt: Option<alloc::boxed::Box<mt::MtCtx>>,
212}
213
214impl core::fmt::Debug for Compressor {
215 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
216 let mut d = f.debug_struct("Compressor");
217 d.field("level", &self.level)
218 .field("dict", &self.dict)
219 .field("checksum", &self.fparams.checksum);
220 #[cfg(feature = "std")]
221 d.field("workers", &self.mt_params.workers);
222 d.finish_non_exhaustive()
223 }
224}
225
226impl Compressor {
227 /// A compressor for `level` (see [`compress`]).
228 pub fn new(level: i32) -> Self {
229 Compressor {
230 level,
231 inner: None,
232 dict: cdict::DictSlot::None,
233 fparams: FrameParams::default(),
234 #[cfg(feature = "std")]
235 mt_params: mt::MtParams::default(),
236 #[cfg(feature = "std")]
237 mt: None,
238 }
239 }
240
241 /// Ends each frame with a content checksum (libzstd's
242 /// `ZSTD_c_checksumFlag`; off by default): the low 32 bits of the
243 /// XXH64 of the frame's content, which decoders verify. It costs 4
244 /// bytes per frame and the time to hash the input.
245 ///
246 /// ```
247 /// let mut c = zstd_native::Compressor::new(3);
248 /// c.set_checksum(true);
249 /// let a = c.compress(b"checked, checked, checked")?;
250 /// assert_eq!(zstd_native::decompress(&a)?, b"checked, checked, checked");
251 /// # Ok::<(), zstd_native::Error>(())
252 /// ```
253 pub fn set_checksum(&mut self, on: bool) {
254 self.fparams.checksum = on;
255 }
256
257 /// Writes the content size into the frame header (libzstd's
258 /// `ZSTD_c_contentSizeFlag`; on by default). Off, the header leaves it
259 /// out (decoders then cannot tell the size before decoding); the
260 /// compressed blocks are the same.
261 pub fn set_content_size_flag(&mut self, on: bool) {
262 self.fparams.content_size = on;
263 }
264
265 /// Writes the dictionary's ID into the frame header, when a
266 /// dictionary with an ID is used (libzstd's `ZSTD_c_dictIDFlag`; on by
267 /// default). Off, the header leaves it out (decoders then cannot check
268 /// that they have the right dictionary); the compressed blocks are the
269 /// same.
270 pub fn set_dict_id_flag(&mut self, on: bool) {
271 self.fparams.dict_id = on;
272 }
273
274 /// Compresses with `n` worker threads (libzstd's `ZSTD_c_nbWorkers`; at
275 /// most 256, 64 on 32-bit targets); 0, the default, compresses in the
276 /// calling thread. The output is byte-identical to libzstd's
277 /// `ZSTD_compress2` with the same worker count (a different count
278 /// changes it, see below).
279 ///
280 /// As in libzstd, inputs of at most 512 KiB are still compressed in the
281 /// calling thread; larger ones are cut into jobs (by default `4 <<
282 /// windowLog` bytes, at least 1 MiB: 8 MiB at level 3, 32 MiB at level
283 /// 19), each compressed by a worker starting from the end of the
284 /// previous one, so a frame needs several jobs to use several workers.
285 /// Multithreaded output differs from single-threaded output, and
286 /// compresses slightly less well.
287 ///
288 /// The threads are started at the first frame that uses them and kept
289 /// until the compressor is dropped (or the count changes). Memory: per
290 /// worker, a compressor's tables for the level; per job in flight (at
291 /// most the smallest power of 2 above the worker count plus 2), its
292 /// input and output.
293 ///
294 /// On 32-bit targets, large jobs and many workers can need more memory
295 /// than the address space has: libzstd's round buffer of the input is
296 /// `workers + 3` jobs (`+ 2` without overlap; at least the window plus
297 /// the slack jobs with long distance matching), so with level 22's
298 /// 256 MiB jobs (the largest there) it reaches 2 GiB from 5 workers on.
299 /// Compressing a frame then fails with
300 /// [`Error::MemoryAllocation`](crate::Error::MemoryAllocation), as
301 /// libzstd fails to allocate it (`memory_allocation`).
302 #[cfg(feature = "std")]
303 pub fn set_workers(&mut self, n: u32) {
304 self.mt_params.set_workers(n);
305 }
306
307 /// The worker thread count (see [`set_workers`](Self::set_workers)).
308 #[cfg(feature = "std")]
309 pub fn workers(&self) -> u32 {
310 self.mt_params.workers
311 }
312
313 /// Sets the job size of multithreaded compression (libzstd's
314 /// `ZSTD_c_jobSize`: 0 is automatic, other sizes are raised to 512 KiB
315 /// and lowered to 1 GiB, 256 MiB on 32-bit targets). For tests.
316 #[cfg(feature = "std")]
317 #[doc(hidden)]
318 pub fn set_job_size(&mut self, size: usize) {
319 self.mt_params.set_job_size(size);
320 }
321
322 /// Sets the overlap between jobs of multithreaded compression
323 /// (libzstd's `ZSTD_c_overlapLog`: 0 is automatic, else 1 (none) to 9
324 /// (the whole window)). For tests.
325 ///
326 /// # Panics
327 ///
328 /// If `log` is over 9.
329 #[cfg(feature = "std")]
330 #[doc(hidden)]
331 pub fn set_overlap_log(&mut self, log: u32) {
332 self.mt_params.set_overlap_log(log);
333 }
334
335 /// `ZSTD_compress2` with workers: the multithreaded path for `src`, if
336 /// it is taken; the output written into `dst` (or a new vector if
337 /// `None`).
338 #[cfg(feature = "std")]
339 fn compress_mt(
340 &mut self,
341 src: &[u8],
342 dst: Option<&mut [u8]>,
343 ) -> Option<crate::error::Result<(alloc::vec::Vec<u8>, usize)>> {
344 let pledged = Some(src.len() as u64);
345 if !self.mt_params.applies(pledged) {
346 return None;
347 }
348 Some((|| {
349 let (cd, level) = self.dict.for_frame(self.level)?;
350 let cp = cdict::frame_cparams(level, cd.as_deref(), pledged, 0, false);
351 let ldm = params::ldm_enabled(&cp);
352 let m = self
353 .mt
354 .get_or_insert_with(|| alloc::boxed::Box::new(mt::MtCtx::new()));
355 m.init_frame(&self.mt_params, cp, ldm, cd, pledged, self.fparams)?;
356 match dst {
357 Some(d) => {
358 let p = m.compress(src, d, EndOp::End)?;
359 if p.remaining != 0 {
360 m.abandon();
361 return Err(crate::Error::OutputTooSmall);
362 }
363 Ok((alloc::vec::Vec::new(), p.written))
364 }
365 None => {
366 let mut v = alloc::vec::Vec::with_capacity(compress_bound(src.len()));
367 m.compress_end_to_vec(src, &mut v)?;
368 let n = v.len();
369 Ok((v, n))
370 }
371 }
372 })())
373 }
374
375 /// A compressor for `level` with the dictionary `dict` (see
376 /// [`set_dictionary`](Self::set_dictionary)).
377 ///
378 /// # Errors
379 ///
380 /// [`Error::InvalidDictionary`](crate::Error::InvalidDictionary) if a
381 /// zstd-format dictionary is corrupt.
382 pub fn with_dictionary(level: i32, dict: &[u8]) -> crate::error::Result<Self> {
383 let mut c = Self::new(level);
384 c.set_dictionary(dict)?;
385 Ok(c)
386 }
387
388 /// A compressor with a prepared dictionary, at its level (see
389 /// [`set_prepared_dictionary`](Self::set_prepared_dictionary)).
390 pub fn with_prepared_dictionary(dict: &EncoderDictionary) -> Self {
391 let mut c = Self::new(dict.level());
392 c.set_prepared_dictionary(dict);
393 c
394 }
395
396 /// Changes the level for the next frames. With a prepared dictionary,
397 /// frames take the dictionary's level instead; a dictionary given to
398 /// [`set_dictionary`](Self::set_dictionary) is indexed at the level of
399 /// the first frame that uses it (as in libzstd).
400 pub fn set_level(&mut self, level: i32) {
401 self.level = level;
402 }
403
404 /// Uses `dict` for the next frames (libzstd's
405 /// `ZSTD_CCtx_loadDictionary`), replacing any dictionary; an empty
406 /// `dict` removes it. Zstd-format dictionaries (starting with the
407 /// magic number `0xEC30A437`) and raw content are both accepted, see
408 /// [`EncoderDictionary`]. The dictionary is indexed for the level of the
409 /// next frame, then kept.
410 ///
411 /// # Errors
412 ///
413 /// [`Error::InvalidDictionary`](crate::Error::InvalidDictionary) if a
414 /// zstd-format dictionary is corrupt; the compressor then has no
415 /// dictionary.
416 pub fn set_dictionary(&mut self, dict: &[u8]) -> crate::error::Result<()> {
417 self.dict = cdict::DictSlot::None;
418 self.dict = cdict::DictSlot::local(dict)?;
419 Ok(())
420 }
421
422 /// Uses the prepared `dict` for the next frames, at its level (libzstd's
423 /// `ZSTD_CCtx_refCDict`), replacing any dictionary.
424 pub fn set_prepared_dictionary(&mut self, dict: &EncoderDictionary) {
425 self.dict = cdict::DictSlot::Prepared(dict.inner.clone());
426 }
427
428 /// Removes the dictionary.
429 pub fn clear_dictionary(&mut self) {
430 self.dict = cdict::DictSlot::None;
431 }
432
433 /// Compresses `src` as one frame (see [`compress`]).
434 ///
435 /// # Errors
436 ///
437 /// As [`compress`].
438 pub fn compress(&mut self, src: &[u8]) -> crate::error::Result<alloc::vec::Vec<u8>> {
439 #[cfg(feature = "std")]
440 if let Some(r) = self.compress_mt(src, None) {
441 return r.map(|(v, _)| v);
442 }
443 if !matches!(self.dict, cdict::DictSlot::None) {
444 return compress::compress_dict_with(
445 &mut self.inner,
446 &mut self.dict,
447 src,
448 self.level,
449 false,
450 self.fparams,
451 );
452 }
453 compress::compress_with(&mut self.inner, src, self.level, false, self.fparams)
454 }
455
456 /// Compresses `src` as one frame into `dst` (see [`compress_to_slice`]).
457 ///
458 /// # Errors
459 ///
460 /// As [`compress_to_slice`].
461 pub fn compress_to_slice(&mut self, src: &[u8], dst: &mut [u8]) -> crate::error::Result<usize> {
462 #[cfg(feature = "std")]
463 if let Some(r) = self.compress_mt(src, Some(&mut *dst)) {
464 return r.map(|(_, n)| n);
465 }
466 if !matches!(self.dict, cdict::DictSlot::None) {
467 return compress::compress_dict_to_slice_with(
468 &mut self.inner,
469 &mut self.dict,
470 src,
471 dst,
472 self.level,
473 false,
474 self.fparams,
475 );
476 }
477 compress::compress_to_slice_with(&mut self.inner, src, dst, self.level, false, self.fparams)
478 }
479}