Skip to main content

zstd_native/enc/
cdict.rs

1//! Compression dictionaries: libzstd 1.6.0's `ZSTD_CDict` and how a
2//! compression context uses one (`compress/zstd_compress.c`).
3//!
4//! # Loading (`ZSTD_compress_insertDictionary`)
5//!
6//! A dictionary is either a zstd-format one (magic `0xEC30A437`: an ID,
7//! entropy tables and repcodes, `ZSTD_loadCEntropy`, then content) or raw
8//! content (anything else, `ZSTD_dct_auto`); one under 8 bytes is ignored.
9//! The content goes into the match finder's tables
10//! (`ZSTD_loadDictionaryContent`): the window takes it as its first
11//! segment, at most the last `ZSTD_CURRENT_MAX` bytes (16 MiB for the
12//! tagged tables of a `fast` or `dfast` CDict), and the tables get at most
13//! the last `1 << max(hashLog + 3, chainLog + 1)` bytes. The content stays
14//! in the [`CDict`]'s buffer: a match state's window positions are then in
15//! that buffer ([`Window::base_in_dict`](super::fast::Window::base_in_dict)),
16//! and the first segment of a frame's input, in another buffer, is never
17//! contiguous with it: the dictionary becomes the extDict.
18//!
19//! # A CDict (`ZSTD_createCDict`)
20//!
21//! Its parameters are the level's for an unknown source size and the
22//! dictionary's size (`ZSTD_cpm_createCDict`); its tables are filled with
23//! `ZSTD_dtlm_full`, `fast` and `dfast` ones with tagged indices
24//! (`ZSTD_tfp_forCDict`: `index << 8 | tag`, the "short cache"); its row
25//! match finder (if any) is unsalted.
26//!
27//! # Using it (`ZSTD_compressBegin_internal`)
28//!
29//! For small sources (under 128 KB, or under 6 times the dictionary, or
30//! unknown, or always for a dictionary loaded into a context, whose CDict
31//! has no level), the context starts from the CDict, by
32//! - attaching it (`ZSTD_resetCCtx_byAttachingCDict`) when the source is at
33//!   most `attachDictSizeCutoffs[strategy]` (8 KB for `fast`, `btultra`,
34//!   `btultra2`, 16 KB for `dfast`, 32 KB for the others) or of unknown
35//!   size: the context's own tables are sized for the source, and the match
36//!   finders' `_dictMatchState` variants also search the CDict's tables;
37//! - or copying its tables (`ZSTD_resetCCtx_byCopyingCDict`): the context
38//!   then has the CDict's parameters (with the frame's window), and the
39//!   dictionary is the extDict.
40//!
41//! Otherwise the context is reset with the frame's own parameters and the
42//! content is loaded into its tables again (`ZSTD_dtlm_fast`). Either way
43//! the first block starts with the dictionary's entropy tables and
44//! repcodes, and the frame header holds its ID.
45//!
46//! Not ported: dedicated dictionary search (`ZSTD_c_enableDedicatedDictSearch`,
47//! off by default), the `ZSTD_c_forceAttachDict` and `ZSTD_c_dictIDFlag`
48//! parameters (their defaults are what this does), prefix dictionaries
49//! (`ZSTD_CCtx_refPrefix`).
50//!
51//! With long distance matching, a raw-content dictionary loaded into the
52//! context's tables is also loaded into the LDM table (see the `ldm`
53//! module); a zstd-format one, or one attached or copied from a CDict, is
54//! not (as in libzstd).
55
56use alloc::sync::Arc;
57use alloc::vec::Vec;
58
59use super::compress::EntropyTables;
60use super::fast::{
61    CURRENT_MAX, HASH_READ_SIZE, MatchState, SHORT_CACHE_TAG_BITS, TableLoadMethod,
62    WINDOW_START_INDEX,
63};
64use super::huf_enc::{HufRepeat, huf_read_ctable};
65use super::params::{
66    CONTENTSIZE_UNKNOWN, CParamMode, CParams, ParamSwitch, Strategy, adjust_cparams_internal,
67    get_cparams_internal, resolve_row_match_finder_mode, row_match_finder_used,
68};
69use super::seq_store::{REP_START_VALUE, hash_at, highbit32};
70use super::sequences::FseRepeat;
71use crate::error::{Error, Result};
72use crate::fse::{LL_FSE_LOG, MAX_LL, MAX_ML, MAX_OFF, ML_FSE_LOG};
73
74/// `ZSTD_MAGIC_DICTIONARY`.
75const DICT_MAGIC: u32 = 0xEC30_A437;
76/// `OffFSELog`.
77const OFF_FSE_LOG: u32 = 8;
78/// `ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF`.
79const USE_CDICT_PARAMS_SRCSIZE_CUTOFF: u64 = 128 << 10;
80/// `ZSTD_USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER`.
81const USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER: u64 = 6;
82
83/// `attachDictSizeCutoffs`: per strategy, the source size up to which a
84/// CDict is attached rather than copied.
85const ATTACH_DICT_SIZE_CUTOFFS: [u64; 10] = [
86    8 << 10,  // unused
87    8 << 10,  // ZSTD_fast
88    16 << 10, // ZSTD_dfast
89    32 << 10, // ZSTD_greedy
90    32 << 10, // ZSTD_lazy
91    32 << 10, // ZSTD_lazy2
92    32 << 10, // ZSTD_btlazy2
93    32 << 10, // ZSTD_btopt
94    8 << 10,  // ZSTD_btultra
95    8 << 10,  // ZSTD_btultra2
96];
97
98/// libzstd's `ZSTD_CDict`: a dictionary prepared for compression at a
99/// level (its content, its entropy tables and its match finder tables).
100pub(crate) struct CDict {
101    /// The dictionary as given (`dictContent`; `dictContentSize` is its
102    /// length, entropy header included).
103    pub(crate) content: Vec<u8>,
104    /// `dictID` (0 for raw content).
105    pub(crate) dict_id: u32,
106    /// `compressionLevel`: the level frames using it take; 0
107    /// (`ZSTD_NO_CLEVEL`) for a dictionary loaded into a compressor, whose
108    /// level is the compressor's.
109    pub(crate) level: i32,
110    /// `matchState.cParams` and `useRowMatchFinder` (resolved).
111    pub(crate) cparams: CParams,
112    pub(crate) use_row: bool,
113    /// `matchState`: the tables, with window positions in `content`.
114    pub(crate) ms: MatchState,
115    /// `cBlockState`: the entropy tables and repcodes a frame starts with.
116    pub(crate) entropy: EntropyTables,
117    pub(crate) rep: [u32; 3],
118    /// Where the content loaded into the tables starts (after a zstd
119    /// dictionary's header); `None` for a dictionary under 8 bytes.
120    load_start: Option<usize>,
121}
122
123impl core::fmt::Debug for CDict {
124    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
125        f.debug_struct("CDict")
126            .field("dict_id", &self.dict_id)
127            .field("level", &self.level)
128            .field("content_len", &self.content.len())
129            .field("cparams", &self.cparams)
130            .finish_non_exhaustive()
131    }
132}
133
134impl CDict {
135    /// `ZSTD_createCDict(dict, dictSize, level)` (`ZSTD_dct_auto`): the
136    /// parameters are `level`'s, and frames using it take `level` (the
137    /// default 3 for 0). With `local`, `ZSTD_initLocalDict` instead (the
138    /// dictionary of `ZSTD_CCtx_loadDictionary`): the same tables, but no
139    /// level of its own (`ZSTD_NO_CLEVEL`).
140    ///
141    /// # Errors
142    ///
143    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
144    pub(crate) fn new(data: &[u8], level: i32, local: bool) -> Result<CDict> {
145        let dict_size = data.len() as u64;
146        // ZSTD_getCParamsFromCCtxParams(.., ZSTD_CONTENTSIZE_UNKNOWN,
147        // dictSize, ZSTD_cpm_createCDict): ZSTD_getCParams_internal, then
148        // one more adjustment
149        let unknown = CONTENTSIZE_UNKNOWN;
150        let mode = CParamMode::CreateCDict;
151        let cp = get_cparams_internal(level, unknown, dict_size, mode);
152        let cparams = adjust_cparams_internal(cp, unknown, dict_size, mode, ParamSwitch::Auto);
153        let use_row = row_match_finder_used(
154            cparams.strategy,
155            resolve_row_match_finder_mode(ParamSwitch::Auto, &cparams),
156        );
157        let mut ms = MatchState::new_with(cparams, use_row, true);
158        let mut entropy = EntropyTables::new();
159        let mut rep = REP_START_VALUE;
160        // ZSTD_compress_insertDictionary (ZSTD_dtlm_full, ZSTD_tfp_forCDict)
161        let (dict_id, load_start) = if data.len() < 8 {
162            (0, None)
163        } else if u32::from_le_bytes(data[..4].try_into().unwrap()) != DICT_MAGIC {
164            (0, Some(0)) // raw content dictionary detected
165        } else {
166            let id = u32::from_le_bytes(data[4..8].try_into().unwrap());
167            let e_size;
168            (entropy, rep, e_size) = load_c_entropy(data)?;
169            (id, Some(e_size))
170        };
171        if let Some(s) = load_start {
172            load_dictionary_content(&mut ms, data, s, data.len(), TableLoadMethod::Full, true);
173            if s != 0 {
174                // A zstd-format dictionary (ZSTD_loadZstdDictionary with
175                // ZSTD_tfp_forCDict, libzstd 1.6.0): the match finder may
176                // retain only a suffix of a large dictionary (short-cache
177                // CDicts at most (1 << 24) - 2 bytes). Recheck the repcodes
178                // against the actual window so that dictMatchState searches
179                // cannot underflow their match indices.
180                let w = &ms.window;
181                let loaded_dict_size = w.index(w.next_src) - w.low_limit;
182                check_dictionary_rep_codes(&rep, loaded_dict_size as usize)?;
183            }
184        }
185        let level = if local {
186            0
187        } else if level == 0 {
188            super::params::CLEVEL_DEFAULT
189        } else {
190            level
191        };
192        Ok(CDict {
193            content: data.to_vec(),
194            dict_id,
195            level,
196            cparams,
197            use_row,
198            ms,
199            entropy,
200            rep,
201            load_start,
202        })
203    }
204
205    /// `ZSTD_compress_insertDictionary` of this dictionary into a
206    /// context's (fresh) match state `ms` (`ZSTD_dtlm_fast`,
207    /// `ZSTD_tfp_forCCtx`): loads its content into `ms`'s tables, the
208    /// content staying in `self` (`ms.dict`). The entropy tables and
209    /// repcodes (`self.entropy`, `self.rep`) are the caller's to take.
210    pub(crate) fn load_into(self: &Arc<CDict>, ms: &mut MatchState) {
211        if let Some(s) = self.load_start {
212            ms.dict = Some(self.clone());
213            let end = self.content.len();
214            load_dictionary_content(ms, &self.content, s, end, TableLoadMethod::Fast, false);
215        }
216    }
217
218    /// A raw-content dictionary of at least 8 bytes (loaded with
219    /// `ZSTD_loadDictionaryContent` directly, which also loads it into the
220    /// LDM table).
221    pub(crate) fn is_raw_content(&self) -> bool {
222        self.load_start == Some(0)
223    }
224
225    /// `cdict->matchState.window` holds content (`cdictLen != 0` in
226    /// `ZSTD_resetCCtx_byAttachingCDict`): whether attaching makes sense.
227    pub(crate) fn has_window_content(&self) -> bool {
228        let w = &self.ms.window;
229        w.index(w.next_src) != w.dict_limit
230    }
231}
232
233/// `ZSTD_shouldAttachDict()` (no dedicated dictionary search, no
234/// `ZSTD_c_forceAttachDict`, no `forceWindow`).
235pub(crate) fn should_attach(cd: &CDict, pledged_src_size: u64) -> bool {
236    let cutoff = ATTACH_DICT_SIZE_CUTOFFS[cd.cparams.strategy as usize];
237    pledged_src_size <= cutoff || pledged_src_size == CONTENTSIZE_UNKNOWN
238}
239
240/// The condition of `ZSTD_compressBegin_internal` to start a frame of
241/// `pledged_src_size` bytes from the CDict's tables (attached or copied)
242/// rather than loading its content into tables with the frame's own
243/// parameters.
244pub(crate) fn use_cdict_tables(cd: &CDict, pledged_src_size: u64) -> bool {
245    let len = cd.content.len() as u64;
246    len > 0
247        && (pledged_src_size < USE_CDICT_PARAMS_SRCSIZE_CUTOFF
248            || pledged_src_size < len * USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
249            || pledged_src_size == CONTENTSIZE_UNKNOWN
250            || cd.level == 0)
251}
252
253/// The parameters of a frame of `pledged` bytes (`None`: unknown) at
254/// `level` with the dictionary `cd` (`ZSTD_CCtx_init_compressStream2`:
255/// `ZSTD_getCParamMode`, then `ZSTD_getCParamsFromCCtxParams` with the
256/// dictionary's size and `window_log` as `ZSTD_c_windowLog`, 0 for the
257/// level's). With `force_ldm` (`ZSTD_c_enableLongDistanceMatching` set),
258/// the window log defaults to `ZSTD_LDM_DEFAULT_WINDOW_LOG` instead of the
259/// level's.
260pub(crate) fn frame_cparams(
261    level: i32,
262    cd: Option<&CDict>,
263    pledged: Option<u64>,
264    window_log: u32,
265    force_ldm: bool,
266) -> CParams {
267    let size = pledged.unwrap_or(CONTENTSIZE_UNKNOWN);
268    let dict_size = cd.map_or(0, |c| c.content.len() as u64);
269    let mode = match cd {
270        Some(cd) if should_attach(cd, size) => CParamMode::AttachDict,
271        _ => CParamMode::NoAttachDict,
272    };
273    let mut cp = get_cparams_internal(level, size, dict_size, mode);
274    if force_ldm {
275        cp.window_log = super::ldm::LDM_DEFAULT_WINDOW_LOG;
276    }
277    if window_log != 0 {
278        cp.window_log = window_log; // ZSTD_overrideCParams
279    }
280    adjust_cparams_internal(cp, size, dict_size, mode, ParamSwitch::Auto)
281}
282
283/// `ZSTD_dictNCountRepeat()`: a dictionary's FSE table is `valid` only if
284/// it covers every symbol up to `max_symbol_value` with a non-zero
285/// probability.
286fn dict_ncount_repeat(
287    norm: &[i16],
288    dict_max_symbol_value: u32,
289    max_symbol_value: u32,
290) -> FseRepeat {
291    if dict_max_symbol_value < max_symbol_value {
292        return FseRepeat::Check;
293    }
294    if norm[..=max_symbol_value as usize].contains(&0) {
295        return FseRepeat::Check;
296    }
297    FseRepeat::Valid
298}
299
300/// `ZSTD_loadCEntropy()`: reads a zstd-format dictionary's entropy tables
301/// and repcodes (after its magic number and ID). Returns them and the size
302/// of the header (where the content starts).
303///
304/// # Errors
305///
306/// [`Error::InvalidDictionary`] if they are corrupt.
307fn load_c_entropy(dict: &[u8]) -> Result<(EntropyTables, [u32; 3], usize)> {
308    let bad = Error::InvalidDictionary;
309    let mut e = EntropyTables::new();
310    let mut p = 8;
311
312    // literals: only a table with a weight for every byte is valid
313    e.huf.repeat = HufRepeat::Check;
314    let (huf_size, has_zero_weights) = huf_read_ctable(&mut e.huf.table, &dict[p..])?;
315    if !has_zero_weights && e.huf.table.max_symbol_value == 255 {
316        e.huf.repeat = HufRepeat::Valid;
317    }
318    p += huf_size;
319
320    // offsets: fill all offset symbols to avoid garbage at end of table;
321    // validity is checked once the content size is known
322    let mut of_norm = [0i16; MAX_OFF + 1];
323    let (of_max, of_log, n) =
324        crate::fse::read_ncount(&dict[p..], MAX_OFF, &mut of_norm).map_err(|_| bad)?;
325    if of_log > OFF_FSE_LOG {
326        return Err(bad);
327    }
328    e.fse
329        .of
330        .build(&of_norm, MAX_OFF as u32, of_log)
331        .map_err(|_| bad)?;
332    p += n;
333
334    let mut ml_norm = [0i16; MAX_ML + 1];
335    let (ml_max, ml_log, n) =
336        crate::fse::read_ncount(&dict[p..], MAX_ML, &mut ml_norm).map_err(|_| bad)?;
337    if ml_log > ML_FSE_LOG {
338        return Err(bad);
339    }
340    // the optimal parser reads every symbol's cost, including absent ones:
341    // the table covers the full alphabet (`read_ncount` zero-fills the
342    // omitted counts; libzstd 1.6.0, meta/zstd#4978)
343    e.fse
344        .ml
345        .build(&ml_norm, MAX_ML as u32, ml_log)
346        .map_err(|_| bad)?;
347    e.fse.ml_repeat = dict_ncount_repeat(&ml_norm, ml_max as u32, MAX_ML as u32);
348    p += n;
349
350    let mut ll_norm = [0i16; MAX_LL + 1];
351    let (ll_max, ll_log, n) =
352        crate::fse::read_ncount(&dict[p..], MAX_LL, &mut ll_norm).map_err(|_| bad)?;
353    if ll_log > LL_FSE_LOG {
354        return Err(bad);
355    }
356    // as above, costs for the full symbol range
357    e.fse
358        .ll
359        .build(&ll_norm, MAX_LL as u32, ll_log)
360        .map_err(|_| bad)?;
361    e.fse.ll_repeat = dict_ncount_repeat(&ll_norm, ll_max as u32, MAX_LL as u32);
362    p += n;
363
364    if p + 12 > dict.len() {
365        return Err(bad);
366    }
367    let mut rep = [0u32; 3];
368    for (i, r) in rep.iter_mut().enumerate() {
369        *r = u32::from_le_bytes(dict[p + 4 * i..p + 4 * i + 4].try_into().unwrap());
370    }
371    p += 12;
372
373    let dict_content_size = dict.len() - p;
374    // All offset values <= dictContentSize + 128 KB must be representable
375    // for a valid table
376    let offcode_max = if dict_content_size as u64 <= u64::from(u32::MAX) - (128 << 10) {
377        // the minimum offset code required to represent maxOffset
378        highbit32(dict_content_size as u32 + (128 << 10))
379    } else {
380        MAX_OFF as u32
381    };
382    e.fse.of_repeat = dict_ncount_repeat(&of_norm, of_max as u32, offcode_max.min(MAX_OFF as u32));
383
384    // The format permits nonzero repcodes up to the full content size.
385    check_dictionary_rep_codes(&rep, dict_content_size)?;
386    Ok((e, rep, p))
387}
388
389/// `ZSTD_checkDictionaryRepCodes()` (libzstd 1.6.0): every repcode is
390/// nonzero and at most `dict_content_size`, the addressable content, which
391/// may be smaller than the full dictionary when only a suffix is loaded.
392///
393/// # Errors
394///
395/// [`Error::InvalidDictionary`] otherwise.
396pub(crate) fn check_dictionary_rep_codes(rep: &[u32; 3], dict_content_size: usize) -> Result<()> {
397    if rep
398        .iter()
399        .any(|&r| r == 0 || r as usize > dict_content_size)
400    {
401        return Err(Error::InvalidDictionary);
402    }
403    Ok(())
404}
405
406/// `ZSTD_CDictIndicesAreTagged()`.
407fn indices_are_tagged(cp: &CParams) -> bool {
408    matches!(cp.strategy, Strategy::Fast | Strategy::DFast)
409}
410
411/// `ZSTD_loadDictionaryContent()` (without its LDM part,
412/// `LdmState::load_dictionary`; no `forceWindow`, no
413/// `deterministicRefPrefix`): makes `buf[start..end]` the first segment of
414/// `ms`'s (fresh) window and fills its tables with it, for a CDict
415/// (`for_cdict`: tagged `fast`/`dfast` tables) or a context.
416pub(crate) fn load_dictionary_content(
417    ms: &mut MatchState,
418    buf: &[u8],
419    start: usize,
420    end: usize,
421    dtlm: TableLoadMethod,
422    for_cdict: bool,
423) {
424    load_content(ms, buf, start, end, dtlm, for_cdict, true);
425}
426
427/// `ZSTD_compress_insertDictionary` of a raw-content prefix with
428/// `ZSTD_c_forceMaxWindow` set (`ZSTD_dtlm_fast`, `ZSTD_tfp_forCCtx`), as
429/// the multithreaded compressor loads a job's overlap with the previous
430/// job (`ZSTDMT_compressionJob`): `buf[start..end]` is followed in `buf`
431/// by the data to compress, so the window stays contiguous, and the
432/// prefix is part of the window rather than a dictionary
433/// (`loadedDictEnd = 0`). Prefixes under 8 bytes are ignored.
434pub(crate) fn load_prefix(ms: &mut MatchState, buf: &[u8], start: usize, end: usize) {
435    if end - start >= 8 {
436        load_content(ms, buf, start, end, TableLoadMethod::Fast, false, false);
437    }
438}
439
440/// [`load_dictionary_content`] (`own_buffer`: the content is in the
441/// dictionary's buffer), or the prefix of [`load_prefix`].
442fn load_content(
443    ms: &mut MatchState,
444    buf: &[u8],
445    mut start: usize,
446    end: usize,
447    dtlm: TableLoadMethod,
448    for_cdict: bool,
449    own_buffer: bool,
450) {
451    let cp = ms.cparams;
452    debug_assert!(ms.window.is_empty());
453    {
454        // Ensure large dictionaries can't cause index overflow: allow
455        // indices up to exactly ZSTD_CURRENT_MAX
456        let mut max_dict_size = CURRENT_MAX - WINDOW_START_INDEX;
457        if indices_are_tagged(&cp) && for_cdict {
458            // "short cache" tables hold the index in their top 24 bits
459            let short_cache_max_dict_size =
460                (1u32 << (32 - SHORT_CACHE_TAG_BITS)) - WINDOW_START_INDEX;
461            max_dict_size = max_dict_size.min(short_cache_max_dict_size);
462        }
463        // If the dictionary is too large, only load its suffix.
464        if end - start > max_dict_size as usize {
465            start = end - max_dict_size as usize;
466        }
467    }
468    ms.window.update(start, end - start, false);
469    // the window's positions are now in the dictionary's buffer (a
470    // prefix's are in the caller's)
471    ms.window.base_in_dict = own_buffer;
472
473    // If the dict is larger than we can reasonably index in our tables,
474    // only load the suffix.
475    {
476        let log = (cp.hash_log + 3).max(cp.chain_log + 1).min(31);
477        let max_dict_size = 1usize << log;
478        if end - start > max_dict_size {
479            start = end - max_dict_size;
480        }
481    }
482    ms.next_to_update = ms.window.index(start);
483    // forceWindow (a prefix): no dictionary end, the window rules apply
484    ms.loaded_dict_end = if own_buffer { ms.window.index(end) } else { 0 };
485    ms.force_non_contiguous = false;
486
487    if end - start <= HASH_READ_SIZE {
488        return;
489    }
490    ms.overflow_correct_if_needed(start, end);
491
492    match cp.strategy {
493        Strategy::Fast if for_cdict => ms.fill_hash_table_for_cdict(buf, end, dtlm),
494        Strategy::Fast => ms.fill_hash_table(buf, end, dtlm),
495        Strategy::DFast if for_cdict => {
496            super::dfast::fill_double_hash_table_for_cdict(ms, buf, end, dtlm)
497        }
498        Strategy::DFast => super::dfast::fill_double_hash_table(ms, buf, end, dtlm),
499        Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 => {
500            if ms.use_row_match_finder {
501                ms.tag_table.fill(0);
502                row_update_for_dict(ms, buf, end - HASH_READ_SIZE);
503            } else {
504                insert_hash_chain_for_dict(ms, buf, end - HASH_READ_SIZE);
505            }
506        }
507        // we want the dictionary table fully sorted
508        Strategy::BtLazy2 | Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
509            super::opt::update_tree_for_dict(ms, buf, end)
510        }
511    }
512    ms.next_to_update = ms.window.index(end);
513}
514
515/// `ZSTD_insertAndFindFirstIndex()` for a dictionary's content: inserts
516/// the positions from `nextToUpdate` up to `target` (excluded) into the
517/// hash chains (`mls = minMatch`).
518fn insert_hash_chain_for_dict(ms: &mut MatchState, buf: &[u8], target: usize) {
519    let cp = ms.cparams;
520    let chain_mask = (1u32 << cp.chain_log) - 1;
521    let target = ms.window.index(target);
522    for idx in ms.next_to_update..target {
523        let h = hash_at(buf, ms.window.pos(idx), cp.hash_log, cp.min_match);
524        ms.chain_table[(idx & chain_mask) as usize] = ms.hash_table[h];
525        ms.hash_table[h] = idx;
526    }
527    ms.next_to_update = target;
528}
529
530/// `ZSTD_row_update()` for a dictionary's content (no hash cache, no
531/// skipping): inserts the positions from `nextToUpdate` up to `target`
532/// (excluded) into the rows (`mls = min(minMatch, 6)`).
533fn row_update_for_dict(ms: &mut MatchState, buf: &[u8], target: usize) {
534    let cp = ms.cparams;
535    let row_log = cp.search_log.clamp(4, 6);
536    let row_mask = (1u32 << row_log) - 1;
537    let mls = cp.min_match.min(6);
538    let h_bits = ms.row_hash_log + super::row::ROW_HASH_TAG_BITS;
539    let salt = ms.hash_salt;
540    let target = ms.window.index(target);
541    for idx in ms.next_to_update..target {
542        let p = ms.window.pos(idx);
543        let hash = hash_salted_at(buf, p, h_bits, mls, salt);
544        let rel_row = ((hash >> super::row::ROW_HASH_TAG_BITS) << row_log) as usize;
545        // ZSTD_row_nextIndex: the row's head moves backwards, skipping 0
546        let head = &mut ms.tag_table[rel_row];
547        let mut next = u32::from(head.wrapping_sub(1)) & row_mask;
548        if next == 0 {
549            next = row_mask;
550        }
551        *head = next as u8;
552        ms.tag_table[rel_row + next as usize] = hash as u8;
553        ms.hash_table[rel_row + next as usize] = idx;
554    }
555    ms.next_to_update = target;
556}
557
558/// `ZSTD_hashPtrSalted()` on a buffer position (reads 8 bytes; `mls` 5
559/// and 6, else 4).
560fn hash_salted_at(buf: &[u8], pos: usize, h_bits: u32, mls: u32, salt: u64) -> u32 {
561    use super::seq_store::{PRIME4BYTES, PRIME5BYTES, PRIME6BYTES};
562    let v = u64::from_le_bytes(buf[pos..pos + 8].try_into().unwrap());
563    match mls {
564        5 => (((v << (64 - 40)).wrapping_mul(PRIME5BYTES) ^ salt) >> (64 - h_bits)) as u32,
565        6 => (((v << (64 - 48)).wrapping_mul(PRIME6BYTES) ^ salt) >> (64 - h_bits)) as u32,
566        _ => ((v as u32).wrapping_mul(PRIME4BYTES) ^ salt as u32) >> (32 - h_bits),
567    }
568}
569
570/// A dictionary prepared for compression at a level (libzstd's
571/// `ZSTD_CDict`, `ZSTD_createCDict`): parsed and indexed once, then used by
572/// any number of [`Compressor`](crate::Compressor)s,
573/// [`StreamEncoder`](crate::StreamEncoder)s and [`Encoder`](crate::Encoder)s
574/// (cloning it is cheap: the tables are shared). Frames compressed with it
575/// take its level, and are byte-identical to libzstd's with the same
576/// CDict (`ZSTD_CCtx_refCDict`, the `zstd` crate's
577/// `with_prepared_dictionary`).
578///
579/// Like libzstd's `ZSTD_dct_auto`, data that starts with the dictionary
580/// magic number (`0xEC30A437`) is a zstd-format dictionary (as made by
581/// `zstd --train`: ID, entropy tables, repcodes, content), anything else
582/// raw content. Dictionaries under 8 bytes are ignored (no ID, no
583/// content).
584///
585/// ```
586/// use zstd_native::{Compressor, EncoderDictionary};
587///
588/// let dict = EncoderDictionary::new(b"common words, common phrases", 3)?;
589/// let mut c = Compressor::with_prepared_dictionary(&dict);
590/// let compressed = c.compress(b"common phrases, common words")?;
591///
592/// let mut d = zstd_native::Decompressor::with_dictionary(zstd_native::Dictionary::new(
593///     b"common words, common phrases",
594/// )?);
595/// assert_eq!(d.decompress(&compressed)?, b"common phrases, common words");
596/// # Ok::<(), zstd_native::Error>(())
597/// ```
598#[derive(Clone)]
599pub struct EncoderDictionary {
600    pub(crate) inner: Arc<CDict>,
601}
602
603impl core::fmt::Debug for EncoderDictionary {
604    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
605        f.debug_struct("EncoderDictionary")
606            .field("id", &self.inner.dict_id)
607            .field("level", &self.inner.level)
608            .field("len", &self.inner.content.len())
609            .finish_non_exhaustive()
610    }
611}
612
613impl EncoderDictionary {
614    /// Prepares `dict` for compression at `level` (see
615    /// [`compress`](crate::compress); 0 means the default, 3).
616    ///
617    /// # Errors
618    ///
619    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
620    pub fn new(dict: &[u8], level: i32) -> Result<EncoderDictionary> {
621        Ok(EncoderDictionary {
622            inner: Arc::new(CDict::new(dict, level, false)?),
623        })
624    }
625
626    /// The dictionary ID written in the frames (0 for raw content: none).
627    pub fn id(&self) -> u32 {
628        self.inner.dict_id
629    }
630
631    /// The level frames compressed with it take.
632    pub fn level(&self) -> i32 {
633        self.inner.level
634    }
635}
636
637/// A compressor's dictionary (libzstd's `cctx->localDict` and
638/// `cctx->cdict`).
639#[derive(Clone, Debug, Default)]
640pub(crate) enum DictSlot {
641    /// No dictionary.
642    #[default]
643    None,
644    /// `ZSTD_CCtx_loadDictionary`: the dictionary, and its CDict once made
645    /// (`ZSTD_initLocalDict`, at the start of the first frame, with the
646    /// compressor's level then; kept for later frames).
647    Local {
648        data: Arc<[u8]>,
649        cdict: Option<Arc<CDict>>,
650    },
651    /// `ZSTD_CCtx_refCDict`: frames take its level.
652    Prepared(Arc<CDict>),
653}
654
655impl DictSlot {
656    /// `ZSTD_CCtx_loadDictionary(dict)`: no dictionary if `dict` is
657    /// empty. A zstd-format dictionary's header is checked now (libzstd
658    /// checks it when the first frame starts).
659    ///
660    /// # Errors
661    ///
662    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
663    pub(crate) fn local(dict: &[u8]) -> Result<DictSlot> {
664        if dict.is_empty() {
665            return Ok(DictSlot::None);
666        }
667        if dict.len() >= 8 && u32::from_le_bytes(dict[..4].try_into().unwrap()) == DICT_MAGIC {
668            load_c_entropy(dict)?;
669        }
670        Ok(DictSlot::Local {
671            data: Arc::from(dict),
672            cdict: None,
673        })
674    }
675
676    /// The dictionary of the next frame and the level it takes, for a
677    /// compressor at `level` (`ZSTD_CCtx_init_compressStream2`).
678    ///
679    /// # Errors
680    ///
681    /// [`Error::InvalidDictionary`] if a loaded zstd-format dictionary is
682    /// corrupt (checked when it was loaded).
683    pub(crate) fn for_frame(&mut self, level: i32) -> Result<(Option<Arc<CDict>>, i32)> {
684        match self {
685            DictSlot::None => Ok((None, level)),
686            DictSlot::Local { data, cdict } => {
687                if cdict.is_none() {
688                    *cdict = Some(Arc::new(CDict::new(data, level, true)?));
689                }
690                Ok((cdict.clone(), level))
691            }
692            // Let the cdict's compression level take priority over the
693            // requested params.
694            DictSlot::Prepared(cd) => Ok((Some(cd.clone()), cd.level)),
695        }
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    #[test]
704    fn raw_dictionary() {
705        let data: Vec<u8> = (0..5000u32).map(|i| (i * 7 % 251) as u8).collect();
706        let cd = CDict::new(&data, 3, false).unwrap();
707        assert_eq!(cd.dict_id, 0);
708        assert_eq!(cd.level, 3);
709        assert!(cd.has_window_content());
710        // the window covers the content
711        let w = &cd.ms.window;
712        assert_eq!(w.index(w.next_src) - w.dict_limit, 5000);
713        assert_eq!(cd.ms.loaded_dict_end, w.index(w.next_src));
714        // dfast at level 3: tagged indices in both tables
715        assert_eq!(cd.cparams.strategy, Strategy::DFast);
716        assert!(
717            cd.ms
718                .hash_table
719                .iter()
720                .any(|&v| v >> SHORT_CACHE_TAG_BITS >= 2)
721        );
722    }
723
724    #[test]
725    fn send_sync() {
726        fn check<T: Send + Sync>() {}
727        check::<EncoderDictionary>();
728        check::<crate::Compressor>();
729        check::<crate::StreamEncoder>();
730    }
731
732    #[test]
733    fn tiny_and_corrupt() {
734        let cd = CDict::new(b"abc", 1, false).unwrap();
735        assert!(!cd.has_window_content());
736        assert_eq!(CDict::new(b"abc", 0, true).unwrap().level, 0);
737        assert_eq!(CDict::new(b"abcdefgh", 0, false).unwrap().level, 3);
738        let mut bad = DICT_MAGIC.to_le_bytes().to_vec();
739        bad.extend_from_slice(&[1, 2, 3, 4, 0xFF, 0xFF, 0xFF, 0xFF]);
740        assert!(matches!(
741            CDict::new(&bad, 3, false),
742            Err(Error::InvalidDictionary)
743        ));
744        assert!(DictSlot::local(&bad).is_err());
745        assert!(matches!(DictSlot::local(&[]), Ok(DictSlot::None)));
746    }
747
748    #[test]
749    fn attach_cutoffs() {
750        let data = alloc::vec![7u8; 1000];
751        for (level, cutoff) in [(1, 8 << 10), (3, 16 << 10), (9, 32 << 10), (19, 8 << 10)] {
752            let cd = CDict::new(&data, level, false).unwrap();
753            assert!(should_attach(&cd, cutoff));
754            assert!(!should_attach(&cd, cutoff + 1));
755            assert!(should_attach(&cd, CONTENTSIZE_UNKNOWN));
756        }
757        let cd = CDict::new(&data, 3, false).unwrap();
758        assert!(use_cdict_tables(&cd, (128 << 10) - 1));
759        assert!(!use_cdict_tables(&cd, 128 << 10));
760        assert!(use_cdict_tables(&cd, CONTENTSIZE_UNKNOWN));
761        let local = CDict::new(&data, 3, true).unwrap();
762        assert!(use_cdict_tables(&local, 1 << 30));
763    }
764
765    /// Every strategy's dictMatchState, extDict (copied or loaded tables)
766    /// match finders round trip through the decoder with the dictionary,
767    /// and find matches in the dictionary.
768    #[test]
769    fn round_trip_every_mode() {
770        use super::super::compress::{FrameCompressor, compress_bound};
771        use super::super::fast::tests::{MIRI, texty};
772        // Miri: a smaller dictionary and input, and fewer levels, one per
773        // strategy. Every level attaches (600 bytes: the dictMatchState
774        // match finders take seconds per KB there); fast, dfast and greedy
775        // also copy (1 KiB over their attach cutoff, under 128 KiB: no frame
776        // loads the dictionary into its own tables; the extDict match
777        // finders of every strategy run in the `roundtrip_ring_variants`
778        // tests). Past 10 KB, the input repeats its start: long matches,
779        // cheap there. Whether the dictionary helps is not checked under
780        // Miri.
781        let (dict_len, pieces) = if MIRI { (4000, 8) } else { (20_000, 40) };
782        let dict = texty(dict_len, 1);
783        // the input repeats parts of the dictionary, with other text
784        let mut src = texty(if MIRI { 2000 } else { 30_000 }, 2);
785        for i in 0..pieces {
786            let at = (i * 4999) % (dict_len - 1000);
787            src.extend_from_slice(&dict[at..at + 700]);
788            src.extend_from_slice(&texty(300, 3 + i as u64));
789        }
790        if MIRI {
791            while src.len() < 34 << 10 {
792                src.extend_from_within(..5000);
793            }
794        } else {
795            src.extend_from_slice(&texty(200_000, 50));
796        }
797        let ddict = crate::Dictionary::new(&dict).unwrap();
798        let levels: &[i32] = if MIRI {
799            &[1, 3, 5, 7, 9, 15, 16, 19, 22]
800        } else {
801            &[-3, 1, 2, 3, 4, 5, 7, 8, 9, 12, 15, 16, 17, 19, 22]
802        };
803        for &level in levels {
804            let cd = Arc::new(CDict::new(&dict, level, false).unwrap());
805            let sizes = if MIRI && level <= 5 {
806                let cutoff = ATTACH_DICT_SIZE_CUTOFFS[cd.cparams.strategy as usize];
807                alloc::vec![600, cutoff as usize + 1024]
808            } else if MIRI {
809                alloc::vec![600]
810            } else {
811                alloc::vec![5_000, 20_000, 60_000, src.len()]
812            };
813            let largest = sizes[sizes.len() - 1];
814            for &n in &sizes {
815                let data = &src[..n];
816                let pledged = Some(n as u64);
817                let cp = frame_cparams(cd.level, Some(&cd), pledged, 0, false);
818                let mut slot = None;
819                let fc = FrameCompressor::start_frame(&mut slot, cp, Some(&cd), pledged, false);
820                let attached = fc.ms.dms;
821                let copied_or_loaded = fc.ms.window.base_in_dict;
822                assert_eq!(attached, should_attach(&cd, n as u64), "L{level} n={n}");
823                assert_eq!(copied_or_loaded, !attached, "L{level} n={n}");
824                let mut out = alloc::vec![0u8; compress_bound(n)];
825                let c = fc.compress(&mut out, data).unwrap();
826                let mut d = crate::Decompressor::with_dictionary(ddict.clone());
827                assert_eq!(d.decompress(&out[..c]).unwrap(), data, "L{level} n={n}");
828                if n == largest && !MIRI {
829                    // the dictionary helps with its pieces
830                    let plain = crate::compress(data, cd.level).unwrap();
831                    assert!(c < plain.len(), "L{level} n={n}: {c} vs {}", plain.len());
832                }
833            }
834        }
835    }
836}