Skip to main content

zstd_native/enc/
cdict.rs

1//! Compression dictionaries: libzstd 1.5.7'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        }
174        let level = if local {
175            0
176        } else if level == 0 {
177            super::params::CLEVEL_DEFAULT
178        } else {
179            level
180        };
181        Ok(CDict {
182            content: data.to_vec(),
183            dict_id,
184            level,
185            cparams,
186            use_row,
187            ms,
188            entropy,
189            rep,
190            load_start,
191        })
192    }
193
194    /// `ZSTD_compress_insertDictionary` of this dictionary into a
195    /// context's (fresh) match state `ms` (`ZSTD_dtlm_fast`,
196    /// `ZSTD_tfp_forCCtx`): loads its content into `ms`'s tables, the
197    /// content staying in `self` (`ms.dict`). The entropy tables and
198    /// repcodes (`self.entropy`, `self.rep`) are the caller's to take.
199    pub(crate) fn load_into(self: &Arc<CDict>, ms: &mut MatchState) {
200        if let Some(s) = self.load_start {
201            ms.dict = Some(self.clone());
202            let end = self.content.len();
203            load_dictionary_content(ms, &self.content, s, end, TableLoadMethod::Fast, false);
204        }
205    }
206
207    /// A raw-content dictionary of at least 8 bytes (loaded with
208    /// `ZSTD_loadDictionaryContent` directly, which also loads it into the
209    /// LDM table).
210    pub(crate) fn is_raw_content(&self) -> bool {
211        self.load_start == Some(0)
212    }
213
214    /// `cdict->matchState.window` holds content (`cdictLen != 0` in
215    /// `ZSTD_resetCCtx_byAttachingCDict`): whether attaching makes sense.
216    pub(crate) fn has_window_content(&self) -> bool {
217        let w = &self.ms.window;
218        w.index(w.next_src) != w.dict_limit
219    }
220}
221
222/// `ZSTD_shouldAttachDict()` (no dedicated dictionary search, no
223/// `ZSTD_c_forceAttachDict`, no `forceWindow`).
224pub(crate) fn should_attach(cd: &CDict, pledged_src_size: u64) -> bool {
225    let cutoff = ATTACH_DICT_SIZE_CUTOFFS[cd.cparams.strategy as usize];
226    pledged_src_size <= cutoff || pledged_src_size == CONTENTSIZE_UNKNOWN
227}
228
229/// The condition of `ZSTD_compressBegin_internal` to start a frame of
230/// `pledged_src_size` bytes from the CDict's tables (attached or copied)
231/// rather than loading its content into tables with the frame's own
232/// parameters.
233pub(crate) fn use_cdict_tables(cd: &CDict, pledged_src_size: u64) -> bool {
234    let len = cd.content.len() as u64;
235    len > 0
236        && (pledged_src_size < USE_CDICT_PARAMS_SRCSIZE_CUTOFF
237            || pledged_src_size < len * USE_CDICT_PARAMS_DICTSIZE_MULTIPLIER
238            || pledged_src_size == CONTENTSIZE_UNKNOWN
239            || cd.level == 0)
240}
241
242/// The parameters of a frame of `pledged` bytes (`None`: unknown) at
243/// `level` with the dictionary `cd` (`ZSTD_CCtx_init_compressStream2`:
244/// `ZSTD_getCParamMode`, then `ZSTD_getCParamsFromCCtxParams` with the
245/// dictionary's size and `window_log` as `ZSTD_c_windowLog`, 0 for the
246/// level's). With `force_ldm` (`ZSTD_c_enableLongDistanceMatching` set),
247/// the window log defaults to `ZSTD_LDM_DEFAULT_WINDOW_LOG` instead of the
248/// level's.
249pub(crate) fn frame_cparams(
250    level: i32,
251    cd: Option<&CDict>,
252    pledged: Option<u64>,
253    window_log: u32,
254    force_ldm: bool,
255) -> CParams {
256    let size = pledged.unwrap_or(CONTENTSIZE_UNKNOWN);
257    let dict_size = cd.map_or(0, |c| c.content.len() as u64);
258    let mode = match cd {
259        Some(cd) if should_attach(cd, size) => CParamMode::AttachDict,
260        _ => CParamMode::NoAttachDict,
261    };
262    let mut cp = get_cparams_internal(level, size, dict_size, mode);
263    if force_ldm {
264        cp.window_log = super::ldm::LDM_DEFAULT_WINDOW_LOG;
265    }
266    if window_log != 0 {
267        cp.window_log = window_log; // ZSTD_overrideCParams
268    }
269    adjust_cparams_internal(cp, size, dict_size, mode, ParamSwitch::Auto)
270}
271
272/// `ZSTD_dictNCountRepeat()`: a dictionary's FSE table is `valid` only if
273/// it covers every symbol up to `max_symbol_value` with a non-zero
274/// probability.
275fn dict_ncount_repeat(
276    norm: &[i16],
277    dict_max_symbol_value: u32,
278    max_symbol_value: u32,
279) -> FseRepeat {
280    if dict_max_symbol_value < max_symbol_value {
281        return FseRepeat::Check;
282    }
283    if norm[..=max_symbol_value as usize].contains(&0) {
284        return FseRepeat::Check;
285    }
286    FseRepeat::Valid
287}
288
289/// `ZSTD_loadCEntropy()`: reads a zstd-format dictionary's entropy tables
290/// and repcodes (after its magic number and ID). Returns them and the size
291/// of the header (where the content starts).
292///
293/// # Errors
294///
295/// [`Error::InvalidDictionary`] if they are corrupt.
296fn load_c_entropy(dict: &[u8]) -> Result<(EntropyTables, [u32; 3], usize)> {
297    let bad = Error::InvalidDictionary;
298    let mut e = EntropyTables::new();
299    let mut p = 8;
300
301    // literals: only a table with a weight for every byte is valid
302    e.huf.repeat = HufRepeat::Check;
303    let (huf_size, has_zero_weights) = huf_read_ctable(&mut e.huf.table, &dict[p..])?;
304    if !has_zero_weights && e.huf.table.max_symbol_value == 255 {
305        e.huf.repeat = HufRepeat::Valid;
306    }
307    p += huf_size;
308
309    // offsets: fill all offset symbols to avoid garbage at end of table;
310    // validity is checked once the content size is known
311    let mut of_norm = [0i16; MAX_OFF + 1];
312    let (of_max, of_log, n) =
313        crate::fse::read_ncount(&dict[p..], MAX_OFF, &mut of_norm).map_err(|_| bad)?;
314    if of_log > OFF_FSE_LOG {
315        return Err(bad);
316    }
317    e.fse
318        .of
319        .build(&of_norm, MAX_OFF as u32, of_log)
320        .map_err(|_| bad)?;
321    p += n;
322
323    let mut ml_norm = [0i16; MAX_ML + 1];
324    let (ml_max, ml_log, n) =
325        crate::fse::read_ncount(&dict[p..], MAX_ML, &mut ml_norm).map_err(|_| bad)?;
326    if ml_log > ML_FSE_LOG {
327        return Err(bad);
328    }
329    e.fse
330        .ml
331        .build(&ml_norm, ml_max as u32, ml_log)
332        .map_err(|_| bad)?;
333    e.fse.ml_repeat = dict_ncount_repeat(&ml_norm, ml_max as u32, MAX_ML as u32);
334    p += n;
335
336    let mut ll_norm = [0i16; MAX_LL + 1];
337    let (ll_max, ll_log, n) =
338        crate::fse::read_ncount(&dict[p..], MAX_LL, &mut ll_norm).map_err(|_| bad)?;
339    if ll_log > LL_FSE_LOG {
340        return Err(bad);
341    }
342    e.fse
343        .ll
344        .build(&ll_norm, ll_max as u32, ll_log)
345        .map_err(|_| bad)?;
346    e.fse.ll_repeat = dict_ncount_repeat(&ll_norm, ll_max as u32, MAX_LL as u32);
347    p += n;
348
349    if p + 12 > dict.len() {
350        return Err(bad);
351    }
352    let mut rep = [0u32; 3];
353    for (i, r) in rep.iter_mut().enumerate() {
354        *r = u32::from_le_bytes(dict[p + 4 * i..p + 4 * i + 4].try_into().unwrap());
355    }
356    p += 12;
357
358    let dict_content_size = dict.len() - p;
359    // All offset values <= dictContentSize + 128 KB must be representable
360    // for a valid table
361    let offcode_max = if dict_content_size as u64 <= u64::from(u32::MAX) - (128 << 10) {
362        // the minimum offset code required to represent maxOffset
363        highbit32(dict_content_size as u32 + (128 << 10))
364    } else {
365        MAX_OFF as u32
366    };
367    e.fse.of_repeat = dict_ncount_repeat(&of_norm, of_max as u32, offcode_max.min(MAX_OFF as u32));
368
369    // All repCodes must be <= dictContentSize and != 0
370    if rep
371        .iter()
372        .any(|&r| r == 0 || r as usize > dict_content_size)
373    {
374        return Err(bad);
375    }
376    Ok((e, rep, p))
377}
378
379/// `ZSTD_CDictIndicesAreTagged()`.
380fn indices_are_tagged(cp: &CParams) -> bool {
381    matches!(cp.strategy, Strategy::Fast | Strategy::DFast)
382}
383
384/// `ZSTD_loadDictionaryContent()` (without its LDM part,
385/// `LdmState::load_dictionary`; no `forceWindow`, no
386/// `deterministicRefPrefix`): makes `buf[start..end]` the first segment of
387/// `ms`'s (fresh) window and fills its tables with it, for a CDict
388/// (`for_cdict`: tagged `fast`/`dfast` tables) or a context.
389pub(crate) fn load_dictionary_content(
390    ms: &mut MatchState,
391    buf: &[u8],
392    start: usize,
393    end: usize,
394    dtlm: TableLoadMethod,
395    for_cdict: bool,
396) {
397    load_content(ms, buf, start, end, dtlm, for_cdict, true);
398}
399
400/// `ZSTD_compress_insertDictionary` of a raw-content prefix with
401/// `ZSTD_c_forceMaxWindow` set (`ZSTD_dtlm_fast`, `ZSTD_tfp_forCCtx`), as
402/// the multithreaded compressor loads a job's overlap with the previous
403/// job (`ZSTDMT_compressionJob`): `buf[start..end]` is followed in `buf`
404/// by the data to compress, so the window stays contiguous, and the
405/// prefix is part of the window rather than a dictionary
406/// (`loadedDictEnd = 0`). Prefixes under 8 bytes are ignored.
407pub(crate) fn load_prefix(ms: &mut MatchState, buf: &[u8], start: usize, end: usize) {
408    if end - start >= 8 {
409        load_content(ms, buf, start, end, TableLoadMethod::Fast, false, false);
410    }
411}
412
413/// [`load_dictionary_content`] (`own_buffer`: the content is in the
414/// dictionary's buffer), or the prefix of [`load_prefix`].
415fn load_content(
416    ms: &mut MatchState,
417    buf: &[u8],
418    mut start: usize,
419    end: usize,
420    dtlm: TableLoadMethod,
421    for_cdict: bool,
422    own_buffer: bool,
423) {
424    let cp = ms.cparams;
425    debug_assert!(ms.window.is_empty());
426    {
427        // Ensure large dictionaries can't cause index overflow: allow
428        // indices up to exactly ZSTD_CURRENT_MAX
429        let mut max_dict_size = CURRENT_MAX - WINDOW_START_INDEX;
430        if indices_are_tagged(&cp) && for_cdict {
431            // "short cache" tables hold the index in their top 24 bits
432            let short_cache_max_dict_size =
433                (1u32 << (32 - SHORT_CACHE_TAG_BITS)) - WINDOW_START_INDEX;
434            max_dict_size = max_dict_size.min(short_cache_max_dict_size);
435        }
436        // If the dictionary is too large, only load its suffix.
437        if end - start > max_dict_size as usize {
438            start = end - max_dict_size as usize;
439        }
440    }
441    ms.window.update(start, end - start, false);
442    // the window's positions are now in the dictionary's buffer (a
443    // prefix's are in the caller's)
444    ms.window.base_in_dict = own_buffer;
445
446    // If the dict is larger than we can reasonably index in our tables,
447    // only load the suffix.
448    {
449        let log = (cp.hash_log + 3).max(cp.chain_log + 1).min(31);
450        let max_dict_size = 1usize << log;
451        if end - start > max_dict_size {
452            start = end - max_dict_size;
453        }
454    }
455    ms.next_to_update = ms.window.index(start);
456    // forceWindow (a prefix): no dictionary end, the window rules apply
457    ms.loaded_dict_end = if own_buffer { ms.window.index(end) } else { 0 };
458    ms.force_non_contiguous = false;
459
460    if end - start <= HASH_READ_SIZE {
461        return;
462    }
463    ms.overflow_correct_if_needed(start, end);
464
465    match cp.strategy {
466        Strategy::Fast if for_cdict => ms.fill_hash_table_for_cdict(buf, end, dtlm),
467        Strategy::Fast => ms.fill_hash_table(buf, end, dtlm),
468        Strategy::DFast if for_cdict => {
469            super::dfast::fill_double_hash_table_for_cdict(ms, buf, end, dtlm)
470        }
471        Strategy::DFast => super::dfast::fill_double_hash_table(ms, buf, end, dtlm),
472        Strategy::Greedy | Strategy::Lazy | Strategy::Lazy2 => {
473            if ms.use_row_match_finder {
474                ms.tag_table.fill(0);
475                row_update_for_dict(ms, buf, end - HASH_READ_SIZE);
476            } else {
477                insert_hash_chain_for_dict(ms, buf, end - HASH_READ_SIZE);
478            }
479        }
480        // we want the dictionary table fully sorted
481        Strategy::BtLazy2 | Strategy::BtOpt | Strategy::BtUltra | Strategy::BtUltra2 => {
482            super::opt::update_tree_for_dict(ms, buf, end)
483        }
484    }
485    ms.next_to_update = ms.window.index(end);
486}
487
488/// `ZSTD_insertAndFindFirstIndex()` for a dictionary's content: inserts
489/// the positions from `nextToUpdate` up to `target` (excluded) into the
490/// hash chains (`mls = minMatch`).
491fn insert_hash_chain_for_dict(ms: &mut MatchState, buf: &[u8], target: usize) {
492    let cp = ms.cparams;
493    let chain_mask = (1u32 << cp.chain_log) - 1;
494    let target = ms.window.index(target);
495    for idx in ms.next_to_update..target {
496        let h = hash_at(buf, ms.window.pos(idx), cp.hash_log, cp.min_match);
497        ms.chain_table[(idx & chain_mask) as usize] = ms.hash_table[h];
498        ms.hash_table[h] = idx;
499    }
500    ms.next_to_update = target;
501}
502
503/// `ZSTD_row_update()` for a dictionary's content (no hash cache, no
504/// skipping): inserts the positions from `nextToUpdate` up to `target`
505/// (excluded) into the rows (`mls = min(minMatch, 6)`).
506fn row_update_for_dict(ms: &mut MatchState, buf: &[u8], target: usize) {
507    let cp = ms.cparams;
508    let row_log = cp.search_log.clamp(4, 6);
509    let row_mask = (1u32 << row_log) - 1;
510    let mls = cp.min_match.min(6);
511    let h_bits = ms.row_hash_log + super::row::ROW_HASH_TAG_BITS;
512    let salt = ms.hash_salt;
513    let target = ms.window.index(target);
514    for idx in ms.next_to_update..target {
515        let p = ms.window.pos(idx);
516        let hash = hash_salted_at(buf, p, h_bits, mls, salt);
517        let rel_row = ((hash >> super::row::ROW_HASH_TAG_BITS) << row_log) as usize;
518        // ZSTD_row_nextIndex: the row's head moves backwards, skipping 0
519        let head = &mut ms.tag_table[rel_row];
520        let mut next = u32::from(head.wrapping_sub(1)) & row_mask;
521        if next == 0 {
522            next = row_mask;
523        }
524        *head = next as u8;
525        ms.tag_table[rel_row + next as usize] = hash as u8;
526        ms.hash_table[rel_row + next as usize] = idx;
527    }
528    ms.next_to_update = target;
529}
530
531/// `ZSTD_hashPtrSalted()` on a buffer position (reads 8 bytes; `mls` 5
532/// and 6, else 4).
533fn hash_salted_at(buf: &[u8], pos: usize, h_bits: u32, mls: u32, salt: u64) -> u32 {
534    use super::seq_store::{PRIME4BYTES, PRIME5BYTES, PRIME6BYTES};
535    let v = u64::from_le_bytes(buf[pos..pos + 8].try_into().unwrap());
536    match mls {
537        5 => (((v << (64 - 40)).wrapping_mul(PRIME5BYTES) ^ salt) >> (64 - h_bits)) as u32,
538        6 => (((v << (64 - 48)).wrapping_mul(PRIME6BYTES) ^ salt) >> (64 - h_bits)) as u32,
539        _ => ((v as u32).wrapping_mul(PRIME4BYTES) ^ salt as u32) >> (32 - h_bits),
540    }
541}
542
543/// A dictionary prepared for compression at a level (libzstd's
544/// `ZSTD_CDict`, `ZSTD_createCDict`): parsed and indexed once, then used by
545/// any number of [`Compressor`](crate::Compressor)s,
546/// [`StreamEncoder`](crate::StreamEncoder)s and [`Encoder`](crate::Encoder)s
547/// (cloning it is cheap: the tables are shared). Frames compressed with it
548/// take its level, and are byte-identical to libzstd's with the same
549/// CDict (`ZSTD_CCtx_refCDict`, the `zstd` crate's
550/// `with_prepared_dictionary`).
551///
552/// Like libzstd's `ZSTD_dct_auto`, data that starts with the dictionary
553/// magic number (`0xEC30A437`) is a zstd-format dictionary (as made by
554/// `zstd --train`: ID, entropy tables, repcodes, content), anything else
555/// raw content. Dictionaries under 8 bytes are ignored (no ID, no
556/// content).
557///
558/// ```
559/// use zstd_native::{Compressor, EncoderDictionary};
560///
561/// let dict = EncoderDictionary::new(b"common words, common phrases", 3)?;
562/// let mut c = Compressor::with_prepared_dictionary(&dict);
563/// let compressed = c.compress(b"common phrases, common words")?;
564///
565/// let mut d = zstd_native::Decompressor::with_dictionary(zstd_native::Dictionary::new(
566///     b"common words, common phrases",
567/// )?);
568/// assert_eq!(d.decompress(&compressed)?, b"common phrases, common words");
569/// # Ok::<(), zstd_native::Error>(())
570/// ```
571#[derive(Clone)]
572pub struct EncoderDictionary {
573    pub(crate) inner: Arc<CDict>,
574}
575
576impl core::fmt::Debug for EncoderDictionary {
577    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
578        f.debug_struct("EncoderDictionary")
579            .field("id", &self.inner.dict_id)
580            .field("level", &self.inner.level)
581            .field("len", &self.inner.content.len())
582            .finish_non_exhaustive()
583    }
584}
585
586impl EncoderDictionary {
587    /// Prepares `dict` for compression at `level` (see
588    /// [`compress`](crate::compress); 0 means the default, 3).
589    ///
590    /// # Errors
591    ///
592    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
593    pub fn new(dict: &[u8], level: i32) -> Result<EncoderDictionary> {
594        Ok(EncoderDictionary {
595            inner: Arc::new(CDict::new(dict, level, false)?),
596        })
597    }
598
599    /// The dictionary ID written in the frames (0 for raw content: none).
600    pub fn id(&self) -> u32 {
601        self.inner.dict_id
602    }
603
604    /// The level frames compressed with it take.
605    pub fn level(&self) -> i32 {
606        self.inner.level
607    }
608}
609
610/// A compressor's dictionary (libzstd's `cctx->localDict` and
611/// `cctx->cdict`).
612#[derive(Clone, Debug, Default)]
613pub(crate) enum DictSlot {
614    /// No dictionary.
615    #[default]
616    None,
617    /// `ZSTD_CCtx_loadDictionary`: the dictionary, and its CDict once made
618    /// (`ZSTD_initLocalDict`, at the start of the first frame, with the
619    /// compressor's level then; kept for later frames).
620    Local {
621        data: Arc<[u8]>,
622        cdict: Option<Arc<CDict>>,
623    },
624    /// `ZSTD_CCtx_refCDict`: frames take its level.
625    Prepared(Arc<CDict>),
626}
627
628impl DictSlot {
629    /// `ZSTD_CCtx_loadDictionary(dict)`: no dictionary if `dict` is
630    /// empty. A zstd-format dictionary's header is checked now (libzstd
631    /// checks it when the first frame starts).
632    ///
633    /// # Errors
634    ///
635    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
636    pub(crate) fn local(dict: &[u8]) -> Result<DictSlot> {
637        if dict.is_empty() {
638            return Ok(DictSlot::None);
639        }
640        if dict.len() >= 8 && u32::from_le_bytes(dict[..4].try_into().unwrap()) == DICT_MAGIC {
641            load_c_entropy(dict)?;
642        }
643        Ok(DictSlot::Local {
644            data: Arc::from(dict),
645            cdict: None,
646        })
647    }
648
649    /// The dictionary of the next frame and the level it takes, for a
650    /// compressor at `level` (`ZSTD_CCtx_init_compressStream2`).
651    ///
652    /// # Errors
653    ///
654    /// [`Error::InvalidDictionary`] if a loaded zstd-format dictionary is
655    /// corrupt (checked when it was loaded).
656    pub(crate) fn for_frame(&mut self, level: i32) -> Result<(Option<Arc<CDict>>, i32)> {
657        match self {
658            DictSlot::None => Ok((None, level)),
659            DictSlot::Local { data, cdict } => {
660                if cdict.is_none() {
661                    *cdict = Some(Arc::new(CDict::new(data, level, true)?));
662                }
663                Ok((cdict.clone(), level))
664            }
665            // Let the cdict's compression level take priority over the
666            // requested params.
667            DictSlot::Prepared(cd) => Ok((Some(cd.clone()), cd.level)),
668        }
669    }
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675
676    #[test]
677    fn raw_dictionary() {
678        let data: Vec<u8> = (0..5000u32).map(|i| (i * 7 % 251) as u8).collect();
679        let cd = CDict::new(&data, 3, false).unwrap();
680        assert_eq!(cd.dict_id, 0);
681        assert_eq!(cd.level, 3);
682        assert!(cd.has_window_content());
683        // the window covers the content
684        let w = &cd.ms.window;
685        assert_eq!(w.index(w.next_src) - w.dict_limit, 5000);
686        assert_eq!(cd.ms.loaded_dict_end, w.index(w.next_src));
687        // dfast at level 3: tagged indices in both tables
688        assert_eq!(cd.cparams.strategy, Strategy::DFast);
689        assert!(
690            cd.ms
691                .hash_table
692                .iter()
693                .any(|&v| v >> SHORT_CACHE_TAG_BITS >= 2)
694        );
695    }
696
697    #[test]
698    fn send_sync() {
699        fn check<T: Send + Sync>() {}
700        check::<EncoderDictionary>();
701        check::<crate::Compressor>();
702        check::<crate::StreamEncoder>();
703    }
704
705    #[test]
706    fn tiny_and_corrupt() {
707        let cd = CDict::new(b"abc", 1, false).unwrap();
708        assert!(!cd.has_window_content());
709        assert_eq!(CDict::new(b"abc", 0, true).unwrap().level, 0);
710        assert_eq!(CDict::new(b"abcdefgh", 0, false).unwrap().level, 3);
711        let mut bad = DICT_MAGIC.to_le_bytes().to_vec();
712        bad.extend_from_slice(&[1, 2, 3, 4, 0xFF, 0xFF, 0xFF, 0xFF]);
713        assert!(matches!(
714            CDict::new(&bad, 3, false),
715            Err(Error::InvalidDictionary)
716        ));
717        assert!(DictSlot::local(&bad).is_err());
718        assert!(matches!(DictSlot::local(&[]), Ok(DictSlot::None)));
719    }
720
721    #[test]
722    fn attach_cutoffs() {
723        let data = alloc::vec![7u8; 1000];
724        for (level, cutoff) in [(1, 8 << 10), (3, 16 << 10), (9, 32 << 10), (19, 8 << 10)] {
725            let cd = CDict::new(&data, level, false).unwrap();
726            assert!(should_attach(&cd, cutoff));
727            assert!(!should_attach(&cd, cutoff + 1));
728            assert!(should_attach(&cd, CONTENTSIZE_UNKNOWN));
729        }
730        let cd = CDict::new(&data, 3, false).unwrap();
731        assert!(use_cdict_tables(&cd, (128 << 10) - 1));
732        assert!(!use_cdict_tables(&cd, 128 << 10));
733        assert!(use_cdict_tables(&cd, CONTENTSIZE_UNKNOWN));
734        let local = CDict::new(&data, 3, true).unwrap();
735        assert!(use_cdict_tables(&local, 1 << 30));
736    }
737
738    /// Every strategy's dictMatchState, extDict (copied or loaded tables)
739    /// match finders round trip through the decoder with the dictionary,
740    /// and find matches in the dictionary.
741    #[test]
742    fn round_trip_every_mode() {
743        use super::super::compress::{FrameCompressor, compress_bound};
744        use super::super::fast::tests::texty;
745        let dict = texty(20_000, 1);
746        // the input repeats parts of the dictionary, with other text
747        let mut src = texty(30_000, 2);
748        for i in 0..40 {
749            let at = (i * 4999) % 19_000;
750            src.extend_from_slice(&dict[at..at + 700]);
751            src.extend_from_slice(&texty(300, 3 + i as u64));
752        }
753        src.extend_from_slice(&texty(200_000, 50));
754        let ddict = crate::Dictionary::new(&dict).unwrap();
755        for level in [-3, 1, 2, 3, 4, 5, 7, 8, 9, 12, 15, 16, 17, 19, 22] {
756            let cd = Arc::new(CDict::new(&dict, level, false).unwrap());
757            for n in [5_000usize, 20_000, 60_000, src.len()] {
758                let data = &src[..n];
759                let pledged = Some(n as u64);
760                let cp = frame_cparams(cd.level, Some(&cd), pledged, 0, false);
761                let mut slot = None;
762                let fc = FrameCompressor::start_frame(&mut slot, cp, Some(&cd), pledged, false);
763                let attached = fc.ms.dms;
764                let copied_or_loaded = fc.ms.window.base_in_dict;
765                assert_eq!(attached, should_attach(&cd, n as u64), "L{level} n={n}");
766                assert_eq!(copied_or_loaded, !attached, "L{level} n={n}");
767                let mut out = alloc::vec![0u8; compress_bound(n)];
768                let c = fc.compress(&mut out, data).unwrap();
769                let mut d = crate::Decompressor::with_dictionary(ddict.clone());
770                assert_eq!(d.decompress(&out[..c]).unwrap(), data, "L{level} n={n}");
771                if n == src.len() {
772                    // the dictionary helps with its pieces
773                    let plain = crate::compress(data, cd.level).unwrap();
774                    assert!(c < plain.len(), "L{level} n={n}: {c} vs {}", plain.len());
775                }
776            }
777        }
778    }
779}