1use 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#[derive(Clone)]
23pub struct Dictionary {
24 inner: Arc<Inner>,
25}
26
27struct Inner {
28 id: u32,
29 content: Vec<u8>,
30 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 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 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 rep in &mut ent.rep {
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 *rep = 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 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 pub fn id(&self) -> u32 {
120 self.inner.id
121 }
122
123 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 pub(crate) fn entropy(&self) -> Option<&DictEntropy> {
134 self.inner.entropy.as_deref()
135 }
136}