Skip to main content

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;
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.5.7'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.5.7'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 level 22's 512 MiB jobs, or a 512 MiB job size, need
298    /// 2 GiB with one worker. Compressing a frame then fails with
299    /// [`Error::MemoryAllocation`](crate::Error::MemoryAllocation), as
300    /// libzstd fails to allocate it (`memory_allocation`).
301    #[cfg(feature = "std")]
302    pub fn set_workers(&mut self, n: u32) {
303        self.mt_params.set_workers(n);
304    }
305
306    /// The worker thread count (see [`set_workers`](Self::set_workers)).
307    #[cfg(feature = "std")]
308    pub fn workers(&self) -> u32 {
309        self.mt_params.workers
310    }
311
312    /// Sets the job size of multithreaded compression (libzstd's
313    /// `ZSTD_c_jobSize`: 0 is automatic, other sizes are raised to 512 KiB
314    /// and lowered to 1 GiB, 512 MiB on 32-bit targets). For tests.
315    #[cfg(feature = "std")]
316    #[doc(hidden)]
317    pub fn set_job_size(&mut self, size: usize) {
318        self.mt_params.set_job_size(size);
319    }
320
321    /// Sets the overlap between jobs of multithreaded compression
322    /// (libzstd's `ZSTD_c_overlapLog`: 0 is automatic, else 1 (none) to 9
323    /// (the whole window)). For tests.
324    ///
325    /// # Panics
326    ///
327    /// If `log` is over 9.
328    #[cfg(feature = "std")]
329    #[doc(hidden)]
330    pub fn set_overlap_log(&mut self, log: u32) {
331        self.mt_params.set_overlap_log(log);
332    }
333
334    /// `ZSTD_compress2` with workers: the multithreaded path for `src`, if
335    /// it is taken; the output written into `dst` (or a new vector if
336    /// `None`).
337    #[cfg(feature = "std")]
338    fn compress_mt(
339        &mut self,
340        src: &[u8],
341        dst: Option<&mut [u8]>,
342    ) -> Option<crate::error::Result<(alloc::vec::Vec<u8>, usize)>> {
343        let pledged = Some(src.len() as u64);
344        if !self.mt_params.applies(pledged) {
345            return None;
346        }
347        Some((|| {
348            let (cd, level) = self.dict.for_frame(self.level)?;
349            let cp = cdict::frame_cparams(level, cd.as_deref(), pledged, 0, false);
350            let ldm = params::ldm_enabled(&cp);
351            let m = self
352                .mt
353                .get_or_insert_with(|| alloc::boxed::Box::new(mt::MtCtx::new()));
354            m.init_frame(&self.mt_params, cp, ldm, cd, pledged, self.fparams)?;
355            match dst {
356                Some(d) => {
357                    let p = m.compress(src, d, EndOp::End)?;
358                    if p.remaining != 0 {
359                        m.abandon();
360                        return Err(crate::Error::OutputTooSmall);
361                    }
362                    Ok((alloc::vec::Vec::new(), p.written))
363                }
364                None => {
365                    let mut v = alloc::vec::Vec::with_capacity(compress_bound(src.len()));
366                    m.compress_end_to_vec(src, &mut v)?;
367                    let n = v.len();
368                    Ok((v, n))
369                }
370            }
371        })())
372    }
373
374    /// A compressor for `level` with the dictionary `dict` (see
375    /// [`set_dictionary`](Self::set_dictionary)).
376    ///
377    /// # Errors
378    ///
379    /// [`Error::InvalidDictionary`](crate::Error::InvalidDictionary) if a
380    /// zstd-format dictionary is corrupt.
381    pub fn with_dictionary(level: i32, dict: &[u8]) -> crate::error::Result<Self> {
382        let mut c = Self::new(level);
383        c.set_dictionary(dict)?;
384        Ok(c)
385    }
386
387    /// A compressor with a prepared dictionary, at its level (see
388    /// [`set_prepared_dictionary`](Self::set_prepared_dictionary)).
389    pub fn with_prepared_dictionary(dict: &EncoderDictionary) -> Self {
390        let mut c = Self::new(dict.level());
391        c.set_prepared_dictionary(dict);
392        c
393    }
394
395    /// Changes the level for the next frames. With a prepared dictionary,
396    /// frames take the dictionary's level instead; a dictionary given to
397    /// [`set_dictionary`](Self::set_dictionary) is indexed at the level of
398    /// the first frame that uses it (as in libzstd).
399    pub fn set_level(&mut self, level: i32) {
400        self.level = level;
401    }
402
403    /// Uses `dict` for the next frames (libzstd's
404    /// `ZSTD_CCtx_loadDictionary`), replacing any dictionary; an empty
405    /// `dict` removes it. Zstd-format dictionaries (starting with the
406    /// magic number `0xEC30A437`) and raw content are both accepted, see
407    /// [`EncoderDictionary`]. The dictionary is indexed for the level of the
408    /// next frame, then kept.
409    ///
410    /// # Errors
411    ///
412    /// [`Error::InvalidDictionary`](crate::Error::InvalidDictionary) if a
413    /// zstd-format dictionary is corrupt; the compressor then has no
414    /// dictionary.
415    pub fn set_dictionary(&mut self, dict: &[u8]) -> crate::error::Result<()> {
416        self.dict = cdict::DictSlot::None;
417        self.dict = cdict::DictSlot::local(dict)?;
418        Ok(())
419    }
420
421    /// Uses the prepared `dict` for the next frames, at its level (libzstd's
422    /// `ZSTD_CCtx_refCDict`), replacing any dictionary.
423    pub fn set_prepared_dictionary(&mut self, dict: &EncoderDictionary) {
424        self.dict = cdict::DictSlot::Prepared(dict.inner.clone());
425    }
426
427    /// Removes the dictionary.
428    pub fn clear_dictionary(&mut self) {
429        self.dict = cdict::DictSlot::None;
430    }
431
432    /// Compresses `src` as one frame (see [`compress`]).
433    ///
434    /// # Errors
435    ///
436    /// As [`compress`].
437    pub fn compress(&mut self, src: &[u8]) -> crate::error::Result<alloc::vec::Vec<u8>> {
438        #[cfg(feature = "std")]
439        if let Some(r) = self.compress_mt(src, None) {
440            return r.map(|(v, _)| v);
441        }
442        if !matches!(self.dict, cdict::DictSlot::None) {
443            return compress::compress_dict_with(
444                &mut self.inner,
445                &mut self.dict,
446                src,
447                self.level,
448                false,
449                self.fparams,
450            );
451        }
452        compress::compress_with(&mut self.inner, src, self.level, false, self.fparams)
453    }
454
455    /// Compresses `src` as one frame into `dst` (see [`compress_to_slice`]).
456    ///
457    /// # Errors
458    ///
459    /// As [`compress_to_slice`].
460    pub fn compress_to_slice(&mut self, src: &[u8], dst: &mut [u8]) -> crate::error::Result<usize> {
461        #[cfg(feature = "std")]
462        if let Some(r) = self.compress_mt(src, Some(&mut *dst)) {
463            return r.map(|(_, n)| n);
464        }
465        if !matches!(self.dict, cdict::DictSlot::None) {
466            return compress::compress_dict_to_slice_with(
467                &mut self.inner,
468                &mut self.dict,
469                src,
470                dst,
471                self.level,
472                false,
473                self.fparams,
474            );
475        }
476        compress::compress_to_slice_with(&mut self.inner, src, dst, self.level, false, self.fparams)
477    }
478}