Skip to main content

zstd_native/enc/
compress.rs

1//! Blocks and frames (libzstd's `zstd_compress.c`: `ZSTD_entropyCompressSeqStore`,
2//! `ZSTD_compressBlock_internal`, `ZSTD_compress_frameChunk`,
3//! `ZSTD_writeFrameHeader`, `ZSTD_writeEpilogue`), one-shot.
4
5use alloc::boxed::Box;
6use alloc::sync::Arc;
7use alloc::vec::Vec;
8
9use super::cdict::{CDict, DictSlot, frame_cparams, should_attach, use_cdict_tables};
10use super::fast::{MatchState, SHORT_CACHE_TAG_BITS, build_seq_store};
11use super::hist::hist_count_codes;
12use super::huf_enc::HufRepeat;
13use super::ldm::{LdmState, RawSeq, RawSeqStore, build_seq_store_ext, build_seq_store_ldm};
14use super::literals::{HufCTables, compress_literals, min_gain};
15use super::opt::DictCosts;
16use super::params::{
17    CONTENTSIZE_UNKNOWN, CParamMode, CParams, ParamSwitch, Strategy, adjust_cparams_internal,
18    block_size_max, block_splitter_enabled, ldm_enabled, one_shot_cparams,
19    resolve_row_match_finder_mode, row_match_finder_used,
20};
21use super::presplit::{FpStats, optimal_block_size};
22use super::seq_store::{
23    LongLengthType, MAX_LL, MAX_ML, REP_START_VALUE, SeqStore, fill_codes, max_nb_seq,
24};
25use super::sequences::{
26    FseCTables, FseRepeat, SET_COMPRESSED, build_ctable, encode_sequences, select_encoding_type,
27};
28use crate::error::{Error, Result};
29use crate::fse::{
30    LL_DEFAULT_NORM, MAX_LL as FSE_MAX_LL, MAX_ML as FSE_MAX_ML, MAX_OFF as FSE_MAX_OFF,
31    ML_DEFAULT_NORM, OF_DEFAULT_NORM,
32};
33use crate::xxhash::Xxh64;
34
35pub(super) const BLOCK_HEADER_SIZE: usize = 3;
36const MIN_CBLOCK_SIZE: usize = 2;
37pub(super) const LONGNBSEQ: usize = 0x7F00;
38pub(super) const DEFAULT_MAX_OFF: u32 = 28;
39pub(super) const RLE_MAX_LENGTH: usize = 25;
40const SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO: usize = 20;
41
42/// libzstd's `ZSTD_entropyCTables_t`.
43#[derive(Clone)]
44pub(crate) struct EntropyTables {
45    pub huf: HufCTables,
46    pub fse: FseCTables,
47}
48
49impl EntropyTables {
50    pub(crate) fn new() -> Self {
51        EntropyTables {
52            huf: HufCTables::new(),
53            fse: FseCTables::new(),
54        }
55    }
56}
57
58/// libzstd's `ZSTD_COMPRESSBOUND`: the largest compressed size of `n` bytes.
59pub const fn compress_bound(n: usize) -> usize {
60    n + (n >> 8)
61        + if n < (128 << 10) {
62            ((128 << 10) - n) >> 11
63        } else {
64            0
65        }
66}
67
68/// libzstd's `ZSTD_literalsCompressionIsDisabled` (default mode: only the
69/// fast strategy with acceleration, i.e. negative levels).
70fn literals_compression_disabled(cp: &CParams) -> bool {
71    cp.strategy == Strategy::Fast && cp.target_length > 0
72}
73
74/// A run of sequences of the seq store and their literals: the whole
75/// block, or a partition of it for the block splitter (libzstd derives a
76/// `SeqStore_t` with moved pointers, `ZSTD_deriveSeqStoreChunk`).
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub(crate) struct SeqChunk {
79    /// The sequences `seq_start..seq_end` (and their codes).
80    pub(crate) seq_start: usize,
81    pub(crate) seq_end: usize,
82    /// The literals `lit_start..lit_end` of the literal buffer.
83    pub(crate) lit_start: usize,
84    pub(crate) lit_end: usize,
85    /// The long length, relative to `seq_start` (inside the chunk: libzstd
86    /// 1.6.0 no longer keeps one just past it, meta/zstd#5013).
87    pub(crate) long_length_type: LongLengthType,
88    pub(crate) long_length_pos: u32,
89}
90
91impl SeqChunk {
92    /// The whole store.
93    pub(crate) fn full(ss: &SeqStore) -> Self {
94        SeqChunk {
95            seq_start: 0,
96            seq_end: ss.nb_seq,
97            lit_start: 0,
98            lit_end: ss.lit_len,
99            long_length_type: ss.long_length_type,
100            long_length_pos: ss.long_length_pos,
101        }
102    }
103
104    /// The number of sequences.
105    #[inline]
106    pub(crate) fn nb_seq(&self) -> usize {
107        self.seq_end - self.seq_start
108    }
109}
110
111/// `ZSTD_seqToCodes()` on a chunk: fills the code tables for its
112/// sequences. Returns libzstd's `longOffsets` (only possible on 32-bit
113/// targets).
114pub(crate) fn chunk_to_codes(ss: &mut SeqStore, ch: &SeqChunk) -> bool {
115    let (s, e) = (ch.seq_start, ch.seq_end);
116    let long_offsets = fill_codes(
117        &ss.sequences[s..e],
118        &mut ss.ll_code[s..e],
119        &mut ss.of_code[s..e],
120        &mut ss.ml_code[s..e],
121    );
122    let p = s + ch.long_length_pos as usize;
123    debug_assert!(ch.long_length_type == LongLengthType::None || p < e);
124    match ch.long_length_type {
125        LongLengthType::LiteralLength => ss.ll_code[p] = MAX_LL,
126        LongLengthType::MatchLength => ss.ml_code[p] = MAX_ML,
127        _ => {}
128    }
129    long_offsets
130}
131
132/// libzstd's `ZSTD_symbolEncodingTypeStats_t`.
133#[derive(Clone, Copy, Debug)]
134pub(crate) struct SeqStats {
135    pub(crate) ll_type: u32,
136    pub(crate) of_type: u32,
137    pub(crate) ml_type: u32,
138    /// Size of the table descriptions written.
139    pub(crate) size: usize,
140    /// Size of the last compressed table description (0 if none).
141    pub(crate) last_count_size: usize,
142}
143
144/// libzstd's `ZSTD_buildSequencesStatistics`: computes the codes of the
145/// chunk's sequences (at least one), chooses each code's table encoding,
146/// builds `next`'s tables and writes their descriptions to `dst`.
147pub(crate) fn build_sequences_statistics(
148    dst: &mut [u8],
149    ss: &mut SeqStore,
150    ch: &SeqChunk,
151    prev: &FseCTables,
152    next: &mut FseCTables,
153    strategy: u32,
154) -> Result<SeqStats> {
155    let nb_seq = ch.nb_seq();
156    debug_assert!(nb_seq != 0);
157    chunk_to_codes(ss, ch);
158    let mut count = [0u32; 256];
159    let mut stats = SeqStats {
160        ll_type: 0,
161        of_type: 0,
162        ml_type: 0,
163        size: 0,
164        last_count_size: 0,
165    };
166    let mut op = 0usize;
167    let (ll_codes, of_codes, ml_codes) = (
168        &ss.ll_code[ch.seq_start..ch.seq_end],
169        &ss.of_code[ch.seq_start..ch.seq_end],
170        &ss.ml_code[ch.seq_start..ch.seq_end],
171    );
172
173    // build CTable for Literal Lengths
174    let mut max = FSE_MAX_LL as u32;
175    let most = hist_count_codes(&mut count, &mut max, ll_codes) as usize;
176    next.ll_repeat = prev.ll_repeat;
177    stats.ll_type = select_encoding_type(
178        &mut next.ll_repeat,
179        &count,
180        max,
181        most,
182        nb_seq,
183        9,
184        &prev.ll,
185        &LL_DEFAULT_NORM,
186        6,
187        true,
188        strategy,
189    );
190    let n = build_ctable(
191        &mut dst[op..],
192        &mut next.ll,
193        9,
194        stats.ll_type,
195        &mut count,
196        max,
197        ll_codes,
198        &LL_DEFAULT_NORM,
199        6,
200        FSE_MAX_LL as u32,
201        &prev.ll,
202    )?;
203    if stats.ll_type == SET_COMPRESSED {
204        stats.last_count_size = n;
205    }
206    op += n;
207
208    // build CTable for Offsets
209    let mut max = FSE_MAX_OFF as u32;
210    let most = hist_count_codes(&mut count, &mut max, of_codes) as usize;
211    // the basic table can only be used if max <= DefaultMaxOff, otherwise
212    // the offsets are too large
213    let default_allowed = max <= DEFAULT_MAX_OFF;
214    next.of_repeat = prev.of_repeat;
215    stats.of_type = select_encoding_type(
216        &mut next.of_repeat,
217        &count,
218        max,
219        most,
220        nb_seq,
221        8,
222        &prev.of,
223        &OF_DEFAULT_NORM,
224        5,
225        default_allowed,
226        strategy,
227    );
228    let n = build_ctable(
229        &mut dst[op..],
230        &mut next.of,
231        8,
232        stats.of_type,
233        &mut count,
234        max,
235        of_codes,
236        &OF_DEFAULT_NORM,
237        5,
238        DEFAULT_MAX_OFF,
239        &prev.of,
240    )?;
241    if stats.of_type == SET_COMPRESSED {
242        stats.last_count_size = n;
243    }
244    op += n;
245
246    // build CTable for MatchLengths
247    let mut max = FSE_MAX_ML as u32;
248    let most = hist_count_codes(&mut count, &mut max, ml_codes) as usize;
249    next.ml_repeat = prev.ml_repeat;
250    stats.ml_type = select_encoding_type(
251        &mut next.ml_repeat,
252        &count,
253        max,
254        most,
255        nb_seq,
256        9,
257        &prev.ml,
258        &ML_DEFAULT_NORM,
259        6,
260        true,
261        strategy,
262    );
263    let n = build_ctable(
264        &mut dst[op..],
265        &mut next.ml,
266        9,
267        stats.ml_type,
268        &mut count,
269        max,
270        ml_codes,
271        &ML_DEFAULT_NORM,
272        6,
273        FSE_MAX_ML as u32,
274        &prev.ml,
275    )?;
276    if stats.ml_type == SET_COMPRESSED {
277        stats.last_count_size = n;
278    }
279    op += n;
280    stats.size = op;
281    Ok(stats)
282}
283
284/// libzstd's `ZSTD_entropyCompressSeqStore` (with `_internal` and
285/// `_wExtLitBuffer`) on the chunk `ch` of `ss`, from a block (or
286/// partition) of `block_size` bytes. Returns 0 when it should be stored
287/// raw.
288pub(crate) fn entropy_compress_seq_store(
289    dst: &mut [u8],
290    ss: &mut SeqStore,
291    ch: &SeqChunk,
292    prev: &EntropyTables,
293    next: &mut EntropyTables,
294    cp: &CParams,
295    block_size: usize,
296) -> Result<usize> {
297    let r = entropy_compress_internal(dst, ss, ch, prev, next, cp);
298    let c = match r {
299        Ok(0) => return Ok(0),
300        Err(Error::OutputTooSmall) if block_size <= dst.len() => return Ok(0),
301        Err(e) => return Err(e),
302        Ok(c) => c,
303    };
304    let max_c = block_size - min_gain(block_size, cp.strategy as u32);
305    if c >= max_c {
306        return Ok(0);
307    }
308    Ok(c)
309}
310
311fn entropy_compress_internal(
312    dst: &mut [u8],
313    ss: &mut SeqStore,
314    ch: &SeqChunk,
315    prev: &EntropyTables,
316    next: &mut EntropyTables,
317    cp: &CParams,
318) -> Result<usize> {
319    let strategy = cp.strategy as u32;
320    let nb_seq = ch.nb_seq();
321    let lit_size = ch.lit_end - ch.lit_start;
322    let mut op = 0usize;
323    {
324        let suspect = nb_seq == 0 || lit_size / nb_seq >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO;
325        op += compress_literals(
326            dst,
327            &ss.lit_buf[ch.lit_start..ch.lit_end],
328            &prev.huf,
329            &mut next.huf,
330            strategy,
331            literals_compression_disabled(cp),
332            suspect,
333        )?;
334    }
335    if dst.len() - op < 3 + 1 {
336        return Err(Error::OutputTooSmall);
337    }
338    if nb_seq < 128 {
339        dst[op] = nb_seq as u8;
340        op += 1;
341    } else if nb_seq < LONGNBSEQ {
342        dst[op] = ((nb_seq >> 8) + 0x80) as u8;
343        dst[op + 1] = nb_seq as u8;
344        op += 2;
345    } else {
346        dst[op] = 0xFF;
347        dst[op + 1..op + 3].copy_from_slice(&((nb_seq - LONGNBSEQ) as u16).to_le_bytes());
348        op += 3;
349    }
350    if nb_seq == 0 {
351        next.fse.clone_from(&prev.fse);
352        return Ok(op);
353    }
354
355    let seq_head = op;
356    op += 1;
357    let stats =
358        build_sequences_statistics(&mut dst[op..], ss, ch, &prev.fse, &mut next.fse, strategy)?;
359    op += stats.size;
360    dst[seq_head] = ((stats.ll_type << 6) + (stats.of_type << 4) + (stats.ml_type << 2)) as u8;
361
362    let (s, e) = (ch.seq_start, ch.seq_end);
363    let bitstream = encode_sequences(
364        &mut dst[op..],
365        &next.fse,
366        &ss.ll_code[s..e],
367        &ss.of_code[s..e],
368        &ss.ml_code[s..e],
369        &ss.sequences[s..e],
370    )?;
371    op += bitstream;
372    // zstd <= 1.3.4 decoders reject a last table description under 4 bytes
373    // together with the bitstream: libzstd stores such blocks raw.
374    if stats.last_count_size != 0 && stats.last_count_size + bitstream < 4 {
375        return Ok(0);
376    }
377    Ok(op)
378}
379
380/// libzstd's `ZSTD_isRLE`.
381pub(super) fn is_rle(src: &[u8]) -> bool {
382    src.iter().all(|&b| b == src[0])
383}
384
385/// libzstd's `ZSTD_compressionStage_e` (`cctx->stage`) for a started frame.
386#[derive(Clone, Copy, Debug, PartialEq, Eq)]
387pub(crate) enum FrameStage {
388    /// `ZSTDcs_init`: the frame header is not written yet.
389    Init,
390    /// `ZSTDcs_ongoing`: blocks are being written.
391    Ongoing,
392    /// `ZSTDcs_ending`: the last block was written.
393    Ending,
394}
395
396/// The frame parameters (libzstd's `ZSTD_frameParameters`): what the frame
397/// header declares and whether the frame ends with a content checksum.
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399pub(crate) struct FrameParams {
400    /// `ZSTD_c_contentSizeFlag`: the header holds the content size when it
401    /// is known (default on).
402    pub(crate) content_size: bool,
403    /// `ZSTD_c_checksumFlag`: the frame ends with the low 32 bits of the
404    /// content's XXH64 (default off).
405    pub(crate) checksum: bool,
406    /// `ZSTD_c_dictIDFlag`: the header holds the dictionary's ID, if any
407    /// (default on).
408    pub(crate) dict_id: bool,
409}
410
411impl Default for FrameParams {
412    fn default() -> Self {
413        FrameParams {
414            content_size: true,
415            checksum: false,
416            dict_id: true,
417        }
418    }
419}
420
421/// Compression state for one frame at a time (libzstd's `ZSTD_CCtx`
422/// without the streaming buffers, see [`StreamEncoder`](super::stream::StreamEncoder)).
423pub(crate) struct FrameCompressor {
424    pub(super) cp: CParams,
425    pub(super) ms: MatchState,
426    pub(super) ss: SeqStore,
427    /// `blockState.prevCBlock->entropy`
428    pub(super) prev: Box<EntropyTables>,
429    /// `blockState.nextCBlock->entropy`
430    pub(super) next: Box<EntropyTables>,
431    /// `blockState.prevCBlock->rep`
432    pub(super) rep: [u32; 3],
433    fp: Box<FpStats>,
434    /// `isFirstBlock`
435    pub(super) first_block: bool,
436    /// The post-block splitter is enabled (`ZSTD_blockSplitterEnabled`).
437    split: bool,
438    /// `blockSizeMax`
439    pub(super) block_size_max: usize,
440    /// `stage`
441    pub(super) stage: FrameStage,
442    /// `pledgedSrcSizePlusOne - 1`: the frame's content size, if known.
443    pledged: Option<u64>,
444    /// `consumedSrcSize` and `producedCSize` for the frame.
445    consumed: u64,
446    produced: u64,
447    /// `dictID`: the frame's dictionary ID (0: none written).
448    dict_id: u32,
449    /// `ldmState` (kept between frames for its tables), used when
450    /// [`ldm_on`](Self::ldm_on).
451    pub(super) ldm: Option<Box<LdmState>>,
452    /// Long distance matching is enabled for the frame
453    /// (`appliedParams.ldmParams.enableLdm`).
454    pub(super) ldm_on: bool,
455    /// `externSeqStore`: long matches given from outside (a multithreaded
456    /// job's, see the `mt` module), used while not empty.
457    pub(super) ext: RawSeqStore,
458    /// Scratch space for [`build_seq_store_ext`].
459    ext_view: Vec<RawSeq>,
460    /// `appliedParams.fParams`, see [`set_frame_params`](Self::set_frame_params).
461    fparams: FrameParams,
462    /// `xxhState`: the XXH64 of the frame's content, with
463    /// [`FrameParams::checksum`].
464    xxh: Xxh64,
465}
466
467impl FrameCompressor {
468    pub(crate) fn new(level: i32, src_size: usize) -> Self {
469        let cp = one_shot_cparams(level, src_size as u64);
470        Self::with_params(cp, Some(src_size as u64), ldm_enabled(&cp))
471    }
472
473    /// A compressor for a frame of `pledged` bytes (`None`: unknown) with
474    /// the resolved parameters `cp`, with long distance matching if `ldm`.
475    pub(crate) fn with_params(cp: CParams, pledged: Option<u64>, ldm: bool) -> Self {
476        let bsm = block_size_max(&cp, pledged.unwrap_or(CONTENTSIZE_UNKNOWN));
477        FrameCompressor {
478            ldm: ldm.then(|| Box::new(LdmState::new(&cp, bsm))),
479            ldm_on: ldm,
480            cp,
481            ms: MatchState::new(cp),
482            ss: SeqStore::new(bsm, cp.min_match),
483            prev: Box::new(EntropyTables::new()),
484            next: Box::new(EntropyTables::new()),
485            rep: REP_START_VALUE,
486            fp: Box::new(FpStats::new()),
487            first_block: true,
488            split: block_splitter_enabled(&cp),
489            block_size_max: bsm,
490            stage: FrameStage::Init,
491            pledged,
492            consumed: 0,
493            produced: 0,
494            dict_id: 0,
495            ext: RawSeqStore::default(),
496            ext_view: Vec::new(),
497            fparams: FrameParams::default(),
498            xxh: Xxh64::new(),
499        }
500    }
501
502    /// Prepares for a new frame of `src_size` bytes at `level`, reusing the
503    /// buffers (libzstd's `ZSTD_resetCCtx_internal` with a clean match state
504    /// and `ZSTD_reset_compressedBlockState`).
505    pub(crate) fn reset(&mut self, level: i32, src_size: usize) {
506        let cp = one_shot_cparams(level, src_size as u64);
507        self.reset_with_params(cp, Some(src_size as u64), ldm_enabled(&cp), true);
508    }
509
510    /// As [`reset`](Self::reset), with resolved parameters, a frame of
511    /// `pledged` bytes (`None`: unknown) and long distance matching if
512    /// `ldm`. With `keep_indices` (no dictionary follows), the match state
513    /// continues its indices when it can
514    /// ([`MatchState::reset_keep_indices`]).
515    pub(crate) fn reset_with_params(
516        &mut self,
517        cp: CParams,
518        pledged: Option<u64>,
519        ldm: bool,
520        keep_indices: bool,
521    ) {
522        let use_row = row_match_finder_used(
523            cp.strategy,
524            resolve_row_match_finder_mode(ParamSwitch::Auto, &cp),
525        );
526        self.reset_full(cp, pledged, use_row, &cp, ldm, keep_indices);
527    }
528
529    /// `ZSTD_resetCCtx_internal`: [`reset_with_params`](Self::reset_with_params)
530    /// with the row match finder use given and the post-block splitter
531    /// resolved from the frame's parameters `frame_cp` (with a CDict, `cp`
532    /// holds the CDict's table parameters instead, from which the LDM
533    /// parameters are derived too).
534    fn reset_full(
535        &mut self,
536        cp: CParams,
537        pledged: Option<u64>,
538        use_row: bool,
539        frame_cp: &CParams,
540        ldm: bool,
541        keep_indices: bool,
542    ) {
543        let bsm = block_size_max(&cp, pledged.unwrap_or(CONTENTSIZE_UNKNOWN));
544        self.ldm_on = ldm;
545        if ldm {
546            match self.ldm.as_deref_mut() {
547                Some(l) => l.reset(&cp, bsm),
548                None => self.ldm = Some(Box::new(LdmState::new(&cp, bsm))),
549            }
550        }
551        self.cp = cp;
552        if keep_indices {
553            self.ms.reset_keep_indices(cp, use_row);
554        } else {
555            self.ms.reset_with(cp, use_row, false);
556        }
557        if let Some(o) = self.ms.opt.as_deref_mut() {
558            o.dict_costs = None;
559        }
560        if self.ss.max_nb_lit < bsm || self.ss.max_nb_seq < max_nb_seq(bsm, cp.min_match) {
561            self.ss = SeqStore::new(bsm, cp.min_match);
562        } else {
563            self.ss.reset();
564        }
565        // Table contents don't matter while the repeat modes say none.
566        for e in [&mut self.prev, &mut self.next] {
567            e.huf.repeat = HufRepeat::None;
568            e.fse.ll_repeat = FseRepeat::None;
569            e.fse.of_repeat = FseRepeat::None;
570            e.fse.ml_repeat = FseRepeat::None;
571        }
572        self.rep = REP_START_VALUE;
573        self.first_block = true;
574        self.split = block_splitter_enabled(frame_cp);
575        self.block_size_max = bsm;
576        self.stage = FrameStage::Init;
577        self.pledged = pledged;
578        self.consumed = 0;
579        self.produced = 0;
580        self.dict_id = 0;
581        self.ext.seq.clear();
582        self.ext.pos = 0;
583        self.ext.pos_in_sequence = 0;
584        self.fparams = FrameParams::default();
585        self.xxh = Xxh64::new();
586    }
587
588    /// Sets the frame parameters of the frame just started (the defaults
589    /// after a reset or [`start_frame`](Self::start_frame)), before its
590    /// header is written.
591    pub(crate) fn set_frame_params(&mut self, fp: FrameParams) {
592        debug_assert!(self.stage == FrameStage::Init && self.consumed == 0);
593        self.fparams = fp;
594    }
595
596    /// Starts a frame of `pledged` bytes (`None`: unknown) with the frame
597    /// parameters `frame_cp` (see [`frame_cparams`](super::cdict::frame_cparams))
598    /// and the dictionary `cdict`: libzstd's `ZSTD_compressBegin_internal`,
599    /// which starts from the CDict's tables (attached or copied, see the
600    /// `cdict` module) or loads its content into tables with the frame's
601    /// parameters. Reuses `slot`'s compressor, or makes one. With `ldm`,
602    /// long distance matching is enabled; a raw-content dictionary loaded
603    /// into the tables is loaded into the LDM table too.
604    pub(crate) fn start_frame<'a>(
605        slot: &'a mut Option<Box<FrameCompressor>>,
606        frame_cp: CParams,
607        cdict: Option<&Arc<CDict>>,
608        pledged: Option<u64>,
609        ldm: bool,
610    ) -> &'a mut FrameCompressor {
611        Self::start_frame_impl(slot, frame_cp, cdict, pledged, ldm, true)
612    }
613
614    /// As [`start_frame`](Self::start_frame) without a dictionary, for a
615    /// frame whose prefix is then loaded into the match state
616    /// ([`load_prefix`](super::cdict::load_prefix)): the match state's
617    /// indices restart (no [`MatchState::reset_keep_indices`]).
618    pub(crate) fn start_frame_for_prefix(
619        slot: &mut Option<Box<FrameCompressor>>,
620        frame_cp: CParams,
621        pledged: Option<u64>,
622        ldm: bool,
623    ) -> &mut FrameCompressor {
624        Self::start_frame_impl(slot, frame_cp, None, pledged, ldm, false)
625    }
626
627    fn start_frame_impl<'a>(
628        slot: &'a mut Option<Box<FrameCompressor>>,
629        frame_cp: CParams,
630        cdict: Option<&Arc<CDict>>,
631        pledged: Option<u64>,
632        ldm: bool,
633        keep_indices: bool,
634    ) -> &'a mut FrameCompressor {
635        let fc = match slot {
636            Some(f) => f,
637            None => {
638                // (no LDM tables yet: the reset below makes them)
639                let f = slot.insert(Box::new(FrameCompressor::with_params(
640                    frame_cp, pledged, false,
641                )));
642                // a new context: its one reset below must advance the hash
643                // salt from 0
644                f.ms.clear_hash_salt();
645                f
646            }
647        };
648        let size = pledged.unwrap_or(CONTENTSIZE_UNKNOWN);
649        match cdict {
650            Some(cd) if use_cdict_tables(cd, size) => {
651                if should_attach(cd, size) {
652                    fc.attach_cdict(frame_cp, cd, pledged, ldm);
653                } else {
654                    fc.copy_cdict(frame_cp, cd, pledged, ldm);
655                }
656            }
657            _ => {
658                fc.reset_with_params(frame_cp, pledged, ldm, keep_indices && cdict.is_none());
659                if let Some(cd) = cdict {
660                    // ZSTD_compress_insertDictionary
661                    cd.load_into(&mut fc.ms);
662                    // ZSTD_loadDictionaryContent's LDM part (a zstd-format
663                    // dictionary's content is loaded without the LDM state)
664                    if ldm && cd.is_raw_content() {
665                        let l = fc.ldm.as_deref_mut().expect("LDM state");
666                        l.load_dictionary(cd);
667                    }
668                    fc.take_block_state(cd);
669                }
670            }
671        }
672        fc
673    }
674
675    /// `ZSTD_resetCCtx_byAttachingCDict()`: the context's tables are sized
676    /// for the source only, the match finders search the CDict's too
677    /// (dictMatchState).
678    fn attach_cdict(
679        &mut self,
680        frame_cp: CParams,
681        cd: &Arc<CDict>,
682        pledged: Option<u64>,
683        ldm: bool,
684    ) {
685        let size = pledged.unwrap_or(CONTENTSIZE_UNKNOWN);
686        // Resize working context table params for input only, since the
687        // dict has its own tables.
688        let mut cp = adjust_cparams_internal(
689            cd.cparams,
690            size,
691            cd.content.len() as u64,
692            CParamMode::AttachDict,
693            resolve_row_match_finder_mode(ParamSwitch::Auto, &frame_cp),
694        );
695        cp.window_log = frame_cp.window_log;
696        // ZSTDcrp_makeClean with ZSTDirp_continue (no loaded dictionary
697        // size): the context's indices continue, its tables aren't zeroed
698        // again when their size is unchanged.
699        self.reset_full(cp, pledged, cd.use_row, &frame_cp, ldm, true);
700        debug_assert!(self.cp.strategy == cd.cparams.strategy);
701        // don't even attach dictionaries with no contents
702        if cd.has_window_content() {
703            let w = &cd.ms.window;
704            let cdict_end = w.index(w.next_src);
705            // Enforce the dictMatchState block compressors' repcode bounds
706            // before allowing them to search this dictionary (libzstd
707            // 1.6.0 checks here, returning dictionary_corrupted): CDict::new
708            // already rejects a dictionary whose repcodes exceed the
709            // content its tables keep, and a CDict doesn't change.
710            debug_assert!(
711                super::cdict::check_dictionary_rep_codes(
712                    &cd.rep,
713                    (cdict_end - w.dict_limit) as usize
714                )
715                .is_ok()
716            );
717            let ms = &mut self.ms;
718            ms.dict = Some(cd.clone());
719            ms.dms = true;
720            // prep working match state so dict matches never have negative
721            // indices when they are translated to the working context's
722            // index space
723            if ms.window.dict_limit < cdict_end {
724                ms.window.next_src = ms.window.base.wrapping_add(cdict_end as usize);
725                ms.window.clear();
726            }
727            // loadedDictEnd is expressed within the referential of the
728            // active context
729            ms.loaded_dict_end = ms.window.dict_limit;
730        }
731        self.take_block_state(cd);
732    }
733
734    /// `ZSTD_resetCCtx_byCopyingCDict()`: the context gets the CDict's
735    /// table parameters (with the frame's window), tables and window; the
736    /// dictionary is then its extDict.
737    fn copy_cdict(&mut self, frame_cp: CParams, cd: &Arc<CDict>, pledged: Option<u64>, ldm: bool) {
738        let mut cp = cd.cparams;
739        cp.window_log = frame_cp.window_log;
740        self.reset_full(cp, pledged, cd.use_row, &frame_cp, ldm, false);
741        let ms = &mut self.ms;
742        let src = &cd.ms;
743        // copy tables, removing the tags of a fast or dfast CDict's
744        let tagged = matches!(cp.strategy, Strategy::Fast | Strategy::DFast);
745        let copy = |dst: &mut [u32], src: &[u32]| {
746            debug_assert_eq!(dst.len(), src.len());
747            if tagged {
748                for (d, &s) in dst.iter_mut().zip(src) {
749                    *d = s >> SHORT_CACHE_TAG_BITS;
750                }
751            } else {
752                dst.copy_from_slice(src);
753            }
754        };
755        copy(&mut ms.hash_table, &src.hash_table);
756        copy(&mut ms.chain_table, &src.chain_table);
757        if cd.use_row {
758            ms.tag_table.copy_from_slice(&src.tag_table);
759            ms.hash_salt = src.hash_salt;
760        }
761        // copy dictionary offsets (the window is in the CDict's buffer)
762        ms.window = src.window;
763        ms.next_to_update = src.next_to_update;
764        ms.loaded_dict_end = src.loaded_dict_end;
765        ms.dict = Some(cd.clone());
766        self.take_block_state(cd);
767    }
768
769    /// The dictionary's ID, and its entropy tables and repcodes as the
770    /// previous block's (`cdict->cBlockState`), with what the optimal
771    /// parser seeds its statistics from.
772    fn take_block_state(&mut self, cd: &CDict) {
773        self.dict_id = cd.dict_id;
774        (*self.prev).clone_from(&cd.entropy);
775        self.rep = cd.rep;
776        if let Some(o) = self.ms.opt.as_deref_mut() {
777            o.dict_costs = DictCosts::new(&cd.entropy);
778        }
779    }
780
781    /// `ZSTD_buildSeqStore()` for the block `src[start..end]`, with the
782    /// long distance matcher when enabled (see
783    /// [`build_seq_store`] for `rep` and the result).
784    ///
785    /// # Errors
786    ///
787    /// Only with LDM, see [`LdmState::generate_sequences`].
788    #[inline]
789    pub(super) fn build_block_seq_store(
790        &mut self,
791        rep: &mut [u32; 3],
792        src: &[u8],
793        start: usize,
794        end: usize,
795    ) -> Result<bool> {
796        if !self.ext.seq.is_empty() {
797            return Ok(build_seq_store_ext(
798                &mut self.ms,
799                &mut self.ss,
800                rep,
801                &mut self.ext,
802                &mut self.ext_view,
803                src,
804                start,
805                end,
806            ));
807        }
808        match self.ldm.as_deref_mut().filter(|_| self.ldm_on) {
809            None => Ok(build_seq_store(
810                &mut self.ms,
811                &mut self.ss,
812                rep,
813                src,
814                start,
815                end,
816            )),
817            Some(l) => build_seq_store_ldm(&mut self.ms, &mut self.ss, rep, l, src, start, end),
818        }
819    }
820
821    /// libzstd's `ZSTD_compressBlock_internal`: 0 = store raw, 1 = RLE
822    /// (`dst[0]` holds the byte), else a compressed block's size.
823    fn compress_block(
824        &mut self,
825        dst: &mut [u8],
826        src: &[u8],
827        start: usize,
828        end: usize,
829    ) -> Result<usize> {
830        let mut next_rep = self.rep;
831        let c_size = if !self.build_block_seq_store(&mut next_rep, src, start, end)? {
832            0
833        } else {
834            let ch = SeqChunk::full(&self.ss);
835            let mut c = entropy_compress_seq_store(
836                dst,
837                &mut self.ss,
838                &ch,
839                &self.prev,
840                &mut self.next,
841                &self.cp,
842                end - start,
843            )?;
844            if !self.first_block && c < RLE_MAX_LENGTH && is_rle(&src[start..end]) {
845                c = 1;
846                dst[0] = src[start];
847            }
848            c
849        };
850        if c_size > 1 {
851            core::mem::swap(&mut self.prev, &mut self.next);
852            self.rep = next_rep;
853        }
854        if self.prev.fse.of_repeat == FseRepeat::Valid {
855            self.prev.fse.of_repeat = FseRepeat::Check;
856        }
857        Ok(c_size)
858    }
859
860    /// libzstd's `ZSTD_compress_frameChunk`: compresses `buf[start..end]`
861    /// (already in the window) as blocks of at most `blockSizeMax` bytes,
862    /// the pre-splitter deciding their sizes; with `last_chunk`, the last
863    /// one ends the frame. Returns the size written.
864    fn frame_chunk(
865        &mut self,
866        dst: &mut [u8],
867        buf: &[u8],
868        start: usize,
869        end: usize,
870        last_chunk: bool,
871    ) -> Result<usize> {
872        let bsm = self.block_size_max;
873        let mut savings = self.consumed as i64 - self.produced as i64;
874        let mut op = 0usize;
875        let mut pos = start;
876        while pos < end {
877            let bs = optimal_block_size(
878                &buf[pos..end],
879                bsm,
880                0,
881                self.cp.strategy,
882                savings,
883                &mut self.fp,
884            );
885            let last = u32::from(last_chunk && bs == end - pos);
886            if dst.len() - op < BLOCK_HEADER_SIZE + MIN_CBLOCK_SIZE + 1 {
887                return Err(Error::OutputTooSmall);
888            }
889            self.ms.prepare_block(pos, bs);
890            let c_size = if self.split {
891                self.compress_block_split(&mut dst[op..], buf, pos, pos + bs, last)?
892            } else {
893                let c =
894                    self.compress_block(&mut dst[op + BLOCK_HEADER_SIZE..], buf, pos, pos + bs)?;
895                if c == 0 {
896                    // ZSTD_noCompressBlock
897                    if bs + BLOCK_HEADER_SIZE > dst.len() - op {
898                        return Err(Error::OutputTooSmall);
899                    }
900                    let h = last + ((bs as u32) << 3);
901                    dst[op..op + 3].copy_from_slice(&h.to_le_bytes()[..3]);
902                    dst[op + 3..op + 3 + bs].copy_from_slice(&buf[pos..pos + bs]);
903                    bs + BLOCK_HEADER_SIZE
904                } else {
905                    let h = if c == 1 {
906                        last + (1 << 1) + ((bs as u32) << 3)
907                    } else {
908                        last + (2 << 1) + ((c as u32) << 3)
909                    };
910                    dst[op..op + 3].copy_from_slice(&h.to_le_bytes()[..3]);
911                    c + BLOCK_HEADER_SIZE
912                }
913            };
914            savings += bs as i64 - c_size as i64;
915            pos += bs;
916            op += c_size;
917            self.first_block = false;
918        }
919        if last_chunk && op > 0 {
920            self.stage = FrameStage::Ending;
921        }
922        Ok(op)
923    }
924
925    /// libzstd's `ZSTD_compressContinue_internal` (frame mode): writes the
926    /// frame header on the first call, appends `buf[start..end]` to the
927    /// window and compresses it. Returns the size written.
928    ///
929    /// # Errors
930    ///
931    /// [`Error::OutputTooSmall`], or [`Error::SrcSizeWrong`] when more than
932    /// the pledged size was given.
933    pub(super) fn compress_continue(
934        &mut self,
935        dst: &mut [u8],
936        buf: &[u8],
937        start: usize,
938        end: usize,
939        last_chunk: bool,
940    ) -> Result<usize> {
941        let mut fh_size = 0;
942        if self.stage == FrameStage::Init {
943            fh_size = write_frame_header(dst, &self.cp, self.pledged, self.dict_id, self.fparams)?;
944            self.stage = FrameStage::Ongoing;
945        }
946        if start == end {
947            return Ok(fh_size);
948        }
949        if self.fparams.checksum {
950            self.xxh.update(&buf[start..end]);
951        }
952        self.ms.update_window(start, end - start);
953        if self.ldm_on {
954            let l = self.ldm.as_deref_mut().expect("LDM state");
955            l.update_window(start, end - start);
956        }
957        let c_size = self.frame_chunk(&mut dst[fh_size..], buf, start, end, last_chunk)?;
958        self.consumed += (end - start) as u64;
959        self.produced += (c_size + fh_size) as u64;
960        if self.pledged.is_some_and(|p| self.consumed > p) {
961            return Err(Error::SrcSizeWrong);
962        }
963        Ok(c_size + fh_size)
964    }
965
966    /// libzstd's `ZSTD_compressEnd_public`: [`compress_continue`](Self::compress_continue)
967    /// with the last chunk, then `ZSTD_writeEpilogue` (an empty last block
968    /// if the last block isn't written yet).
969    ///
970    /// # Errors
971    ///
972    /// As `compress_continue`, and [`Error::SrcSizeWrong`] when the frame
973    /// holds less than the pledged size.
974    pub(super) fn compress_end(
975        &mut self,
976        dst: &mut [u8],
977        buf: &[u8],
978        start: usize,
979        end: usize,
980    ) -> Result<usize> {
981        let mut op = self.compress_continue(dst, buf, start, end, true)?;
982        debug_assert!(self.stage != FrameStage::Init);
983        if self.stage != FrameStage::Ending {
984            // one last empty raw block, marked last
985            if dst.len() - op < BLOCK_HEADER_SIZE {
986                return Err(Error::OutputTooSmall);
987            }
988            dst[op..op + 3].copy_from_slice(&1u32.to_le_bytes()[..3]);
989            op += BLOCK_HEADER_SIZE;
990        }
991        if self.fparams.checksum {
992            // the low 32 bits of the content's XXH64
993            if dst.len() - op < 4 {
994                return Err(Error::OutputTooSmall);
995            }
996            dst[op..op + 4].copy_from_slice(&(self.xxh.digest() as u32).to_le_bytes());
997            op += 4;
998        }
999        self.stage = FrameStage::Init;
1000        if self.pledged.is_some_and(|p| self.consumed != p) {
1001            return Err(Error::SrcSizeWrong);
1002        }
1003        Ok(op)
1004    }
1005
1006    /// Compresses `src` as one frame into `dst`; returns the frame size.
1007    pub(crate) fn compress(&mut self, dst: &mut [u8], src: &[u8]) -> Result<usize> {
1008        debug_assert_eq!(self.pledged, Some(src.len() as u64));
1009        self.compress_end(dst, src, 0, src.len())
1010    }
1011}
1012
1013/// libzstd's `ZSTD_writeFrameHeader`: with the content size when `pledged`
1014/// holds it (and `fp` asks for it), the dictionary ID unless it is 0 (or
1015/// `fp` leaves it out), and the checksum flag of `fp`.
1016fn write_frame_header(
1017    dst: &mut [u8],
1018    cp: &CParams,
1019    pledged: Option<u64>,
1020    dict_id: u32,
1021    fp: FrameParams,
1022) -> Result<usize> {
1023    if dst.len() < 18 {
1024        return Err(Error::OutputTooSmall);
1025    }
1026    let dict_id = if fp.dict_id { dict_id } else { 0 };
1027    let window_size = 1u64 << cp.window_log;
1028    let src_size = pledged.unwrap_or(0);
1029    let content_size_flag = fp.content_size && pledged.is_some();
1030    let single = content_size_flag && window_size >= src_size;
1031    let wlog_byte = ((cp.window_log - 10) << 3) as u8;
1032    let fcs_code = if content_size_flag {
1033        u8::from(src_size >= 256)
1034            + u8::from(src_size >= 65536 + 256)
1035            + u8::from(src_size >= 0xFFFF_FFFF)
1036    } else {
1037        0
1038    };
1039    dst[..4].copy_from_slice(&crate::frame::MAGIC.to_le_bytes());
1040    let dict_id_size_code =
1041        u8::from(dict_id > 0) + u8::from(dict_id >= 256) + u8::from(dict_id >= 65536);
1042    dst[4] = dict_id_size_code
1043        + (u8::from(fp.checksum) << 2)
1044        + (u8::from(single) << 5)
1045        + (fcs_code << 6);
1046    let mut pos = 5;
1047    if !single {
1048        dst[pos] = wlog_byte;
1049        pos += 1;
1050    }
1051    match dict_id_size_code {
1052        0 => {}
1053        1 => {
1054            dst[pos] = dict_id as u8;
1055            pos += 1;
1056        }
1057        2 => {
1058            dst[pos..pos + 2].copy_from_slice(&(dict_id as u16).to_le_bytes());
1059            pos += 2;
1060        }
1061        _ => {
1062            dst[pos..pos + 4].copy_from_slice(&dict_id.to_le_bytes());
1063            pos += 4;
1064        }
1065    }
1066    match fcs_code {
1067        0 => {
1068            if single {
1069                dst[pos] = src_size as u8;
1070                pos += 1;
1071            }
1072        }
1073        1 => {
1074            dst[pos..pos + 2].copy_from_slice(&((src_size - 256) as u16).to_le_bytes());
1075            pos += 2;
1076        }
1077        2 => {
1078            dst[pos..pos + 4].copy_from_slice(&(src_size as u32).to_le_bytes());
1079            pos += 4;
1080        }
1081        _ => {
1082            dst[pos..pos + 8].copy_from_slice(&src_size.to_le_bytes());
1083            pos += 8;
1084        }
1085    }
1086    Ok(pos)
1087}
1088
1089/// Compresses `src` at `level` into `dst` with `fc` (or a new compressor).
1090/// With `fresh`, a reused `fc` behaves like a new one, as libzstd's
1091/// one-shot `ZSTD_compress` (a new context per call); otherwise like a
1092/// reused libzstd context, whose row match finder hash salt changes from
1093/// frame to frame.
1094pub(crate) fn compress_to_slice_with(
1095    fc: &mut Option<Box<FrameCompressor>>,
1096    src: &[u8],
1097    dst: &mut [u8],
1098    level: i32,
1099    fresh: bool,
1100    fp: FrameParams,
1101) -> Result<usize> {
1102    let fc = match fc {
1103        Some(f) => {
1104            if fresh {
1105                f.ms.clear_hash_salt();
1106            }
1107            f.reset(level, src.len());
1108            f
1109        }
1110        None => fc.insert(Box::new(FrameCompressor::new(level, src.len()))),
1111    };
1112    fc.set_frame_params(fp);
1113    fc.compress(dst, src)
1114}
1115
1116/// As [`compress_to_slice_with`], into a new vector.
1117pub(crate) fn compress_with(
1118    fc: &mut Option<Box<FrameCompressor>>,
1119    src: &[u8],
1120    level: i32,
1121    fresh: bool,
1122    fp: FrameParams,
1123) -> Result<Vec<u8>> {
1124    let mut out = alloc::vec![0u8; compress_bound(src.len())];
1125    let n = compress_to_slice_with(fc, src, &mut out, level, fresh, fp)?;
1126    out.truncate(n);
1127    Ok(out)
1128}
1129
1130/// As [`compress_to_slice_with`], with the compressor's dictionary `dict`
1131/// (libzstd's `ZSTD_compress2` on a context with a loaded or referenced
1132/// dictionary; with `fresh`, a new context).
1133pub(crate) fn compress_dict_to_slice_with(
1134    fc: &mut Option<Box<FrameCompressor>>,
1135    dict: &mut DictSlot,
1136    src: &[u8],
1137    dst: &mut [u8],
1138    level: i32,
1139    fresh: bool,
1140    fp: FrameParams,
1141) -> Result<usize> {
1142    let (cd, level) = dict.for_frame(level)?;
1143    let pledged = Some(src.len() as u64);
1144    let frame_cp = frame_cparams(level, cd.as_deref(), pledged, 0, false);
1145    if let Some(f) = fc.as_deref_mut().filter(|_| fresh) {
1146        f.ms.clear_hash_salt();
1147    }
1148    let ldm = ldm_enabled(&frame_cp);
1149    let fc = FrameCompressor::start_frame(fc, frame_cp, cd.as_ref(), pledged, ldm);
1150    fc.set_frame_params(fp);
1151    fc.compress(dst, src)
1152}
1153
1154/// As [`compress_dict_to_slice_with`], into a new vector.
1155pub(crate) fn compress_dict_with(
1156    fc: &mut Option<Box<FrameCompressor>>,
1157    dict: &mut DictSlot,
1158    src: &[u8],
1159    level: i32,
1160    fresh: bool,
1161    fp: FrameParams,
1162) -> Result<Vec<u8>> {
1163    let mut out = alloc::vec![0u8; compress_bound(src.len())];
1164    let n = compress_dict_to_slice_with(fc, dict, src, &mut out, level, fresh, fp)?;
1165    out.truncate(n);
1166    Ok(out)
1167}