1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#[cfg(not(target_has_atomic = "ptr"))]
use alloc::rc::Rc;
#[cfg(target_has_atomic = "ptr")]
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::convert::TryInto;
use crate::decoding::errors::DictionaryDecodeError;
use crate::decoding::scratch::FSEScratch;
use crate::decoding::scratch::HuffmanScratch;
/// Zstandard includes support for "raw content" dictionaries, that store bytes optionally used
/// during sequence execution.
///
/// <https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format>
#[derive(Clone)]
pub struct Dictionary {
/// A 4 byte value used by decoders to check if they can use
/// the correct dictionary.
///
/// Zero means unidentified: a raw-content dictionary has no header to
/// carry an ID, and the frames built from it record none, so it can only
/// be supplied explicitly and never resolved from a frame header.
/// Registration by ID
/// ([`FrameDecoder::add_dict`](crate::decoding::FrameDecoder::add_dict))
/// therefore still requires a non-zero one.
pub id: u32,
/// A dictionary can contain an entropy table, either FSE or
/// Huffman.
pub fse: FSEScratch,
/// A dictionary can contain an entropy table, either FSE or
/// Huffman.
pub huf: HuffmanScratch,
/// The content of a dictionary acts as a "past" in front of data
/// to compress or decompress,
/// so it can be referenced in sequence commands.
/// As long as the amount of data decoded from this frame is less than or
/// equal to Window_Size, sequence commands may specify offsets longer than
/// the total length of decoded output so far to reference back to the
/// dictionary, even parts of the dictionary with offsets larger than Window_Size.
/// After the total output has surpassed Window_Size however,
/// this is no longer allowed and the dictionary is no longer accessible
pub dict_content: Vec<u8>,
/// The 3 most recent offsets are stored so that they can be used
/// during sequence execution, see
/// <https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#repeat-offsets>
/// for more.
pub offset_hist: [u32; 3],
}
/// A parsed dictionary held by however many users need it at once.
///
/// Both sides prime frame after frame from one dictionary, so what they hold is
/// shared rather than copied: `Arc` where atomics exist, `Rc` where they do not.
#[cfg(target_has_atomic = "ptr")]
pub(crate) type SharedDictionary = Arc<Dictionary>;
#[cfg(not(target_has_atomic = "ptr"))]
pub(crate) type SharedDictionary = Rc<Dictionary>;
/// Shared pre-parsed dictionary handle for repeated decoding.
///
/// Uses `Arc` on targets with atomics and falls back to `Rc` otherwise.
#[derive(Clone)]
pub struct DictionaryHandle {
inner: SharedDictionary,
}
/// This 4 byte (little endian) magic number refers to the start of a dictionary
pub const MAGIC_NUM: [u8; 4] = [0x37, 0xA4, 0x30, 0xEC];
impl Dictionary {
/// Heap bytes owned by this dictionary: the content plus the parsed
/// entropy tables' heap (the fixed-size FSE decode arrays are inline,
/// counted by `size_of::<Dictionary>()`).
pub fn heap_bytes(&self) -> usize {
self.dict_content.capacity() + self.fse.heap_bytes() + self.huf.heap_bytes()
}
/// Build a dictionary from raw content bytes (without entropy table sections).
///
/// This is primarily intended for dictionaries produced by the `dict-builder`
/// module, which currently emits raw-content dictionaries.
///
/// An `id` of 0 means the dictionary is unidentified, which is what any
/// plain file used as a dictionary is: frames built with it record no
/// dictionary ID, so it can only ever be supplied explicitly, never
/// resolved from a frame header. Registration by ID
/// ([`FrameDecoder::add_dict`](crate::decoding::FrameDecoder::add_dict))
/// still requires a non-zero one, since the ID is the key it is stored
/// under.
pub fn from_raw_content(
id: u32,
dict_content: Vec<u8>,
) -> Result<Dictionary, DictionaryDecodeError> {
if dict_content.is_empty() {
return Err(DictionaryDecodeError::DictionaryTooSmall { got: 0, need: 1 });
}
Ok(Dictionary {
id,
fse: FSEScratch::new(),
huf: HuffmanScratch::new(),
dict_content,
offset_hist: [1, 4, 8],
})
}
/// Parses the dictionary from `raw`, initializes its tables,
/// and returns a fully constructed [`Dictionary`] whose `id` can be
/// checked against the frame's `dict_id`.
pub fn decode_dict(raw: &[u8]) -> Result<Dictionary, DictionaryDecodeError> {
Self::decode_dict_inner(raw, true)
}
/// Loads whichever kind of dictionary `raw` holds, the way `zstd -D` does:
/// a blob starting with [`MAGIC_NUM`] is a serialized dictionary with
/// entropy tables and an ID, and anything else is taken as raw content,
/// which is why any file can be handed to `-D`. A raw-content dictionary
/// has no ID, so it must be supplied explicitly on both sides — see
/// [`Self::from_raw_content`].
pub fn from_serialized_or_raw_content(raw: &[u8]) -> Result<Dictionary, DictionaryDecodeError> {
if raw.starts_with(&MAGIC_NUM) {
Self::decode_dict(raw)
} else if raw.is_empty() {
// A zero-sized buffer is a dictionary with nothing in it rather
// than a malformed one: `ZSTD_createDDict(NULL, 0)` builds a
// usable `DDict` referencing no content, and
// `ZSTD_CCtx_loadDictionary` with an empty buffer is how a caller
// says "no dictionary". [`Self::from_raw_content`] still refuses
// it, because naming raw content and handing over none is the
// caller asking for a dictionary that cannot exist.
Ok(Dictionary {
id: 0,
fse: FSEScratch::new(),
huf: HuffmanScratch::new(),
dict_content: Vec::new(),
offset_hist: [1, 4, 8],
})
} else {
Self::from_raw_content(0, raw.to_vec())
}
}
/// Parse a dictionary for ENCODER use: builds the entropy
/// probabilities/weights needed by `to_encoder_table` but skips the
/// decode-only work the encoder never reads — the FSE *decoding*
/// tables + their `enrich_*` post-passes, and the HUF decode lookup
/// table (`packed_decode`). Produces a [`Dictionary`] whose FSE
/// `symbol_probabilities` / `accuracy_log` and HUF `bits` /
/// `max_num_bits` match `decode_dict` exactly, so the encoder entropy
/// tables — and thus the emitted frame — are byte-identical; only the
/// wasted decode-table builds are dropped. Offset history + content
/// are parsed the same way.
/// Crate-internal: the returned [`Dictionary`] deliberately has no
/// decode lookup tables (`packed_decode` / FSE `decode`), so it is
/// NOT safe to feed into a [`FrameDecoder`](crate::decoding::FrameDecoder)
/// — Huffman decode would index an empty `packed_decode`. The only caller
/// is `EncoderDictionary::from_bytes`, which wraps the result in the
/// encoder-only `EncoderDictionary` type (no decode path), so this
/// incomplete dictionary can never escape to the decode side. Keeping
/// this `pub(crate)` keeps it off the public `Dictionary` API entirely.
pub(crate) fn decode_dict_for_encoding(
raw: &[u8],
) -> Result<Dictionary, DictionaryDecodeError> {
Self::decode_dict_inner(raw, false)
}
/// Shared dictionary parser. `build_decode_tables` selects whether the
/// FSE/HUF tables get their full decoding tables (FSE decode table +
/// `enrich_*`, HUF `packed_decode`; decoder path) or only the
/// probability/weight parse (encoder path — see
/// [`Self::decode_dict_for_encoding`]).
fn decode_dict_inner(
raw: &[u8],
build_decode_tables: bool,
) -> Result<Dictionary, DictionaryDecodeError> {
const MIN_MAGIC_AND_ID_LEN: usize = 8;
const OFFSET_HISTORY_LEN: usize = 12;
if raw.len() < MIN_MAGIC_AND_ID_LEN {
return Err(DictionaryDecodeError::DictionaryTooSmall {
got: raw.len(),
need: MIN_MAGIC_AND_ID_LEN,
});
}
let mut new_dict = Dictionary {
id: 0,
fse: FSEScratch::new(),
huf: HuffmanScratch::new(),
dict_content: Vec::new(),
offset_hist: [1, 4, 8],
};
let magic_num: [u8; 4] = raw[..4].try_into().expect("optimized away");
if magic_num != MAGIC_NUM {
return Err(DictionaryDecodeError::BadMagicNum { got: magic_num });
}
let dict_id = raw[4..8].try_into().expect("optimized away");
let dict_id = u32::from_le_bytes(dict_id);
if dict_id == 0 {
return Err(DictionaryDecodeError::ZeroDictionaryId);
}
new_dict.id = dict_id;
let raw_tables = &raw[8..];
let huf_size = if build_decode_tables {
new_dict.huf.table.build_decoder(raw_tables)?
} else {
new_dict.huf.table.build_weights_only(raw_tables)?
};
let raw_tables = &raw_tables[huf_size as usize..];
let of_size = if build_decode_tables {
let n = new_dict.fse.offsets.build_decoder(
raw_tables,
crate::decoding::sequence_section_decoder::OF_MAX_LOG,
)?;
new_dict.fse.offsets.enrich_for_offsets();
// Compute the pipeline-gate long-offset share ONCE here, while the
// dictionary handle is built, so the per-decode `init_from_dict`
// path can COPY it instead of re-walking the offsets table on every
// `decode_*_with_dict_handle` call (the dict is immutable, so the
// share never changes after this).
new_dict.fse.offsets_long_share =
crate::decoding::sequence_section_decoder::compute_offsets_long_share(
&new_dict.fse.offsets,
);
n
} else {
new_dict.fse.offsets.read_table_probabilities(
raw_tables,
crate::decoding::sequence_section_decoder::OF_MAX_LOG,
)?
};
let raw_tables = &raw_tables[of_size..];
let ml_size = if build_decode_tables {
let n = new_dict.fse.match_lengths.build_decoder(
raw_tables,
crate::decoding::sequence_section_decoder::ML_MAX_LOG,
)?;
new_dict
.fse
.match_lengths
.enrich_with_packed_seq_meta(&crate::decoding::sequence_section_decoder::ML_META);
n
} else {
new_dict.fse.match_lengths.read_table_probabilities(
raw_tables,
crate::decoding::sequence_section_decoder::ML_MAX_LOG,
)?
};
let raw_tables = &raw_tables[ml_size..];
let ll_size = if build_decode_tables {
let n = new_dict.fse.literal_lengths.build_decoder(
raw_tables,
crate::decoding::sequence_section_decoder::LL_MAX_LOG,
)?;
new_dict
.fse
.literal_lengths
.enrich_with_packed_seq_meta(&crate::decoding::sequence_section_decoder::LL_META);
n
} else {
new_dict.fse.literal_lengths.read_table_probabilities(
raw_tables,
crate::decoding::sequence_section_decoder::LL_MAX_LOG,
)?
};
let raw_tables = &raw_tables[ll_size..];
if raw_tables.len() < OFFSET_HISTORY_LEN {
return Err(DictionaryDecodeError::DictionaryTooSmall {
got: raw_tables.len(),
need: OFFSET_HISTORY_LEN,
});
}
let offset1 = raw_tables[0..4].try_into().expect("optimized away");
let offset1 = u32::from_le_bytes(offset1);
let offset2 = raw_tables[4..8].try_into().expect("optimized away");
let offset2 = u32::from_le_bytes(offset2);
let offset3 = raw_tables[8..12].try_into().expect("optimized away");
let offset3 = u32::from_le_bytes(offset3);
if offset1 == 0 {
return Err(DictionaryDecodeError::ZeroRepeatOffsetInDictionary { index: 0 });
}
if offset2 == 0 {
return Err(DictionaryDecodeError::ZeroRepeatOffsetInDictionary { index: 1 });
}
if offset3 == 0 {
return Err(DictionaryDecodeError::ZeroRepeatOffsetInDictionary { index: 2 });
}
new_dict.offset_hist[0] = offset1;
new_dict.offset_hist[1] = offset2;
new_dict.offset_hist[2] = offset3;
let raw_content = &raw_tables[12..];
new_dict.dict_content.extend(raw_content);
Ok(new_dict)
}
/// Convert this parsed dictionary into a reusable shared handle.
pub fn into_handle(self) -> DictionaryHandle {
DictionaryHandle::from_dictionary(self)
}
}
impl DictionaryHandle {
/// Wrap an already-parsed dictionary in a shared handle.
pub fn from_dictionary(dict: Dictionary) -> Self {
Self {
inner: SharedDictionary::new(dict),
}
}
/// Parse a serialized dictionary and return a reusable shared handle.
pub fn decode_dict(raw: &[u8]) -> Result<Self, DictionaryDecodeError> {
Dictionary::decode_dict(raw).map(Self::from_dictionary)
}
/// Load whichever kind of dictionary `raw` holds, as `ZSTD_createDDict`
/// does: a blob starting with [`MAGIC_NUM`] is a serialized dictionary,
/// anything else is raw content. See
/// [`Dictionary::from_serialized_or_raw_content`].
pub fn from_serialized_or_raw_content(raw: &[u8]) -> Result<Self, DictionaryDecodeError> {
Dictionary::from_serialized_or_raw_content(raw).map(Self::from_dictionary)
}
pub fn id(&self) -> u32 {
self.inner.id
}
pub fn as_dict(&self) -> &Dictionary {
&self.inner
}
}
impl AsRef<Dictionary> for DictionaryHandle {
fn as_ref(&self) -> &Dictionary {
self.as_dict()
}
}
impl From<Dictionary> for DictionaryHandle {
fn from(dict: Dictionary) -> Self {
DictionaryHandle::from_dictionary(dict)
}
}
#[cfg(test)]
mod tests;