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::vec::Vec;
6
7use crate::block::Entropy;
8use crate::error::{Error, Result};
9use crate::fse::{self, LL_KIND, ML_KIND, OF_KIND};
10
11const DICT_MAGIC: u32 = 0xEC30_A437;
12
13/// A decompression dictionary, parsed once and reused for many frames.
14#[derive(Clone)]
15pub struct Dictionary {
16    pub(crate) id: u32,
17    pub(crate) content: Vec<u8>,
18    /// Entropy tables of a zstd-format dictionary; `None` for raw content.
19    pub(crate) entropy: Option<Box<Entropy>>,
20}
21
22impl core::fmt::Debug for Dictionary {
23    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
24        f.debug_struct("Dictionary")
25            .field("id", &self.id)
26            .field("content_len", &self.content.len())
27            .field("has_entropy", &self.entropy.is_some())
28            .finish()
29    }
30}
31
32impl Dictionary {
33    /// Parses a dictionary like libzstd's `ZSTD_dct_auto`: data that starts
34    /// with the dictionary magic number is a zstd dictionary (ID, entropy
35    /// tables, repeat offsets, content); anything else is raw content.
36    ///
37    /// # Errors
38    ///
39    /// [`Error::InvalidDictionary`] if a zstd-format dictionary is corrupt.
40    pub fn new(data: &[u8]) -> Result<Dictionary> {
41        if data.len() < 8 || u32::from_le_bytes(data[..4].try_into().unwrap()) != DICT_MAGIC {
42            return Ok(Self::raw(data));
43        }
44        let id = u32::from_le_bytes(data[4..8].try_into().unwrap());
45        let mut ent = Box::new(Entropy::new());
46        let mut p = 8;
47        p += ent
48            .huf
49            .read(&data[p..])
50            .map_err(|_| Error::InvalidDictionary)?;
51        ent.huf_ok = true;
52        for kind in [OF_KIND, ML_KIND, LL_KIND] {
53            let mut norm = [0i16; fse::MAX_ML + 1];
54            let (max_sym, log, used) = fse::read_ncount(&data[p..], kind.max, &mut norm)
55                .map_err(|_| Error::InvalidDictionary)?;
56            if log > kind.max_log {
57                return Err(Error::InvalidDictionary);
58            }
59            ent.seq.build(
60                kind,
61                &norm,
62                max_sym + 1,
63                log,
64                crate::cpu::Features::detect(),
65            );
66            p += used;
67        }
68        ent.fse_ok = true;
69        if p + 12 > data.len() {
70            return Err(Error::InvalidDictionary);
71        }
72        let content_len = data.len() - (p + 12);
73        for i in 0..3 {
74            let r = u32::from_le_bytes(data[p..p + 4].try_into().unwrap());
75            p += 4;
76            if r == 0 || r as usize > content_len {
77                return Err(Error::InvalidDictionary);
78            }
79            ent.rep[i] = r;
80        }
81        Ok(Dictionary {
82            id,
83            content: data[p..].to_vec(),
84            entropy: Some(ent),
85        })
86    }
87
88    /// A raw content dictionary (ID 0): `data` is only history for matches.
89    pub fn raw(data: &[u8]) -> Dictionary {
90        Dictionary {
91            id: 0,
92            content: data.to_vec(),
93            entropy: None,
94        }
95    }
96
97    /// The dictionary ID (0 for raw content).
98    pub fn id(&self) -> u32 {
99        self.id
100    }
101}