Skip to main content

zstd_native/
dict.rs

1//! Dictionaries (RFC 8878 section 5): zstd-format dictionaries with
2//! entropy tables, and raw content dictionaries.
3
4use alloc::boxed::Box;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7
8use crate::block::DictEntropy;
9use crate::error::{Error, Result};
10use crate::fse::SeqTables;
11use crate::fse::{self, LL_KIND, ML_KIND, OF_KIND};
12use crate::huf::HufDt;
13
14const DICT_MAGIC: u32 = 0xEC30_A437;
15
16/// A decompression dictionary, parsed once and reused for many frames
17/// (libzstd's `ZSTD_DDict`).
18///
19/// Cloning is cheap: clones share the parsed content and tables (like
20/// `ZSTD_DCtx_refDDict`), and a decompressor uses the tables in place
21/// rather than copying them for each frame.
22#[derive(Clone)]
23pub struct Dictionary {
24    inner: Arc<Inner>,
25}
26
27struct Inner {
28    id: u32,
29    content: Vec<u8>,
30    /// Entropy tables of a zstd-format dictionary; `None` for raw content.
31    entropy: Option<Box<DictEntropy>>,
32}
33
34impl core::fmt::Debug for Dictionary {
35    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        f.debug_struct("Dictionary")
37            .field("id", &self.inner.id)
38            .field("content_len", &self.inner.content.len())
39            .field("has_entropy", &self.inner.entropy.is_some())
40            .finish()
41    }
42}
43
44impl Dictionary {
45    /// Parses a dictionary like libzstd's `ZSTD_dct_auto`: data that starts
46    /// with the dictionary magic number is a zstd dictionary (ID, entropy
47    /// tables, repeat offsets, content); anything else is raw content.
48    ///
49    /// # Errors
50    ///
51    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
52    pub fn new(data: &[u8]) -> Result<Dictionary> {
53        if data.len() < 8 || u32::from_le_bytes(data[..4].try_into().unwrap()) != DICT_MAGIC {
54            return Ok(Self::raw(data));
55        }
56        let id = u32::from_le_bytes(data[4..8].try_into().unwrap());
57        // The tables are built in place in their own allocation (as a field
58        // of the `Arc`'s value, they were zeroed on the stack and copied
59        // twice).
60        let mut ent = Box::new(DictEntropy {
61            huf: HufDt::new(),
62            seq: SeqTables::new(),
63            rep: [0; 3],
64        });
65        let mut p = 8;
66        p += ent
67            .huf
68            .read(&data[p..])
69            .map_err(|_| Error::InvalidDictionary)?;
70        for kind in [OF_KIND, ML_KIND, LL_KIND] {
71            let mut norm = [0i16; fse::MAX_ML + 1];
72            let (max_sym, log, used) = fse::read_ncount(&data[p..], kind.max, &mut norm)
73                .map_err(|_| Error::InvalidDictionary)?;
74            if log > kind.max_log {
75                return Err(Error::InvalidDictionary);
76            }
77            ent.seq.build(
78                kind,
79                &norm,
80                max_sym + 1,
81                log,
82                crate::cpu::Features::detect(),
83            );
84            p += used;
85        }
86        if p + 12 > data.len() {
87            return Err(Error::InvalidDictionary);
88        }
89        let content_len = data.len() - (p + 12);
90        for i in 0..3 {
91            let r = u32::from_le_bytes(data[p..p + 4].try_into().unwrap());
92            p += 4;
93            if r == 0 || r as usize > content_len {
94                return Err(Error::InvalidDictionary);
95            }
96            ent.rep[i] = r;
97        }
98        Ok(Dictionary {
99            inner: Arc::new(Inner {
100                id,
101                content: data[p..].to_vec(),
102                entropy: Some(ent),
103            }),
104        })
105    }
106
107    /// A raw content dictionary (ID 0): `data` is only history for matches.
108    pub fn raw(data: &[u8]) -> Dictionary {
109        Dictionary {
110            inner: Arc::new(Inner {
111                id: 0,
112                content: data.to_vec(),
113                entropy: None,
114            }),
115        }
116    }
117
118    /// The dictionary ID (0 for raw content).
119    pub fn id(&self) -> u32 {
120        self.inner.id
121    }
122
123    /// Whether `other` is a clone of this dictionary.
124    pub(crate) fn same(&self, other: &Dictionary) -> bool {
125        Arc::ptr_eq(&self.inner, &other.inner)
126    }
127
128    pub(crate) fn content(&self) -> &[u8] {
129        &self.inner.content
130    }
131
132    /// The entropy tables and repeat offsets frames start with.
133    pub(crate) fn entropy(&self) -> Option<&DictEntropy> {
134        self.inner.entropy.as_deref()
135    }
136}