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