Debian Codegraph @

rust-ext/src/compression_dict.rs

raw
1 // Copyright (c) 2020-present, Gregory Szorc
2 // All rights reserved.
3 //
4 // This software may be modified and distributed under the terms
5 // of the BSD license. See the LICENSE file for details.
6
7 use {
8 crate::{
9 compression_parameters::{get_cctx_parameter, int_to_strategy, ZstdCompressionParameters},
10 zstd_safe::{train_dictionary_fastcover, CCtx, CDict, DCtx, DDict},
11 ZstdError,
12 },
13 pyo3::{
14 buffer::PyBuffer,
15 exceptions::PyValueError,
16 prelude::*,
17 types::{PyBytes, PyList},
18 wrap_pyfunction,
19 },
20 };
21
22 #[pyclass(module = "zstandard.backend_rust")]
23 pub struct ZstdCompressionDict {
24 /// Internal format of dictionary data.
25 content_type: zstd_sys::ZSTD_dictContentType_e,
26
27 /// Segment size.
28 #[pyo3(get)]
29 k: u32,
30
31 /// Dmer size.
32 #[pyo3(get)]
33 d: u32,
34
35 /// Raw dictionary data.
36 ///
37 /// Owned by us.
38 data: Vec<u8>,
39
40 /// Precomputed compression dictionary.
41 cdict: Option<CDict<'static>>,
42
43 /// Precomputed decompression dictionary.
44 ddict: Option<DDict<'static>>,
45 }
46
47 unsafe impl Sync for ZstdCompressionDict {}
48
49 impl ZstdCompressionDict {
50 pub(crate) fn load_into_cctx(&self, cctx: &CCtx) -> PyResult<()> {
51 if let Some(cdict) = &self.cdict {
52 cctx.load_computed_dict(cdict)
53 } else {
54 cctx.load_dict_data(&self.data, self.content_type)
55 }
56 .map_err(|msg| {
57 ZstdError::new_err(format!("could not load compression dictionary: {}", msg))
58 })
59 }
60
61 /// Ensure the DDict is populated.
62 pub(crate) fn ensure_ddict(&mut self) -> PyResult<()> {
63 if self.ddict.is_some() {
64 return Ok(());
65 }
66
67 self.ddict = Some(
68 DDict::from_data(&self.data, self.content_type)
69 .map_err(|msg| ZstdError::new_err(msg))?,
70 );
71
72 Ok(())
73 }
74
75 pub(crate) fn load_into_dctx(&mut self, dctx: &DCtx) -> PyResult<()> {
76 self.ensure_ddict()?;
77
78 dctx.load_prepared_dict(self.ddict.as_ref().unwrap())
79 .map_err(|msg| {
80 ZstdError::new_err(format!("unable to reference prepared dictionary: {}", msg))
81 })
82 }
83 }
84
85 #[pymethods]
86 impl ZstdCompressionDict {
87 #[new]
88 #[pyo3(signature = (buffer, dict_type = None))]
89 fn new(py: Python, buffer: PyBuffer<u8>, dict_type: Option<u32>) -> PyResult<Self> {
90 let dict_type = if dict_type == Some(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_auto as u32)
91 {
92 Ok(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_auto)
93 } else if dict_type == Some(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_fullDict as u32) {
94 Ok(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_fullDict)
95 } else if dict_type == Some(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_rawContent as u32) {
96 Ok(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_rawContent)
97 } else if let Some(value) = dict_type {
98 Err(PyValueError::new_err(format!(
99 "invalid dictionary load mode: {}; must use DICT_TYPE_* constants",
100 value
101 )))
102 } else {
103 Ok(zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_auto)
104 }?;
105
106 let dict_data = buffer.to_vec(py)?;
107
108 Ok(ZstdCompressionDict {
109 content_type: dict_type,
110 k: 0,
111 d: 0,
112 data: dict_data,
113 cdict: None,
114 ddict: None,
115 })
116 }
117
118 fn __len__(&self) -> usize {
119 self.data.len()
120 }
121
122 fn as_bytes<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyBytes>> {
123 Ok(PyBytes::new(py, &self.data))
124 }
125
126 fn dict_id(&self) -> u32 {
127 zstd_safe::get_dict_id(&self.data)
128 .map(u32::from)
129 .unwrap_or(0)
130 }
131
132 #[pyo3(signature = (level=None, compression_params=None))]
133 fn precompute_compress(
134 &mut self,
135 py: Python,
136 level: Option<i32>,
137 compression_params: Option<Py<ZstdCompressionParameters>>,
138 ) -> PyResult<()> {
139 let params = if let Some(level) = level {
140 if compression_params.is_some() {
141 return Err(PyValueError::new_err(
142 "must only specify one of level or compression_params",
143 ));
144 }
145
146 unsafe { zstd_sys::ZSTD_getCParams(level, 0, self.data.len()) }
147 } else if let Some(compression_params) = &compression_params {
148 let source_params = compression_params.borrow(py).params;
149
150 let window_log =
151 get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_windowLog)?;
152 let chain_log =
153 get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_chainLog)?;
154 let hash_log =
155 get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_hashLog)?;
156 let search_log =
157 get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_searchLog)?;
158 let min_match =
159 get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_minMatch)?;
160 let target_length = get_cctx_parameter(
161 source_params,
162 zstd_sys::ZSTD_cParameter::ZSTD_c_targetLength,
163 )?;
164 let strategy =
165 get_cctx_parameter(source_params, zstd_sys::ZSTD_cParameter::ZSTD_c_strategy)?;
166
167 zstd_sys::ZSTD_compressionParameters {
168 windowLog: window_log as u32,
169 chainLog: chain_log as u32,
170 hashLog: hash_log as u32,
171 searchLog: search_log as u32,
172 minMatch: min_match as u32,
173 targetLength: target_length as u32,
174 strategy: int_to_strategy(strategy as u32)?,
175 }
176 } else {
177 return Err(PyValueError::new_err(
178 "must specify one of level or compression_params",
179 ));
180 };
181
182 self.cdict = Some(
183 CDict::from_data(&self.data, self.content_type, params)
184 .map_err(|msg| ZstdError::new_err(msg))?,
185 );
186
187 Ok(())
188 }
189 }
190
191 #[pyfunction]
192 #[pyo3(signature = (
193 dict_size,
194 samples,
195 k=0,
196 d=0,
197 f=0,
198 split_point=0.0,
199 accel=0,
200 notifications=0,
201 dict_id=0,
202 level=0,
203 steps=0,
204 threads=0,
205 ))]
206 fn train_dictionary(
207 dict_size: usize,
208 samples: &Bound<'_, PyList>,
209 k: u32,
210 d: u32,
211 f: u32,
212 split_point: f64,
213 accel: u32,
214 notifications: u32,
215 dict_id: u32,
216 level: i32,
217 steps: u32,
218 threads: i32,
219 ) -> PyResult<ZstdCompressionDict> {
220 let threads = if threads < 0 {
221 num_cpus::get() as u32
222 } else {
223 threads as u32
224 };
225
226 let (d, steps, level) = if steps == 0 && threads == 0 {
227 // Defaults from ZDICT_trainFromBuffer().
228 let d = if d != 0 { d } else { 8 };
229 let steps = if steps != 0 { steps } else { 4 };
230 let level = if level != 0 { level } else { 3 };
231
232 (d, steps, level)
233 } else {
234 (d, steps, level)
235 };
236
237 let params = zstd_sys::ZDICT_fastCover_params_t {
238 k,
239 d,
240 f,
241 steps,
242 nbThreads: threads,
243 splitPoint: split_point,
244 accel,
245 shrinkDict: 0,
246 shrinkDictMaxRegression: 0,
247 zParams: zstd_sys::ZDICT_params_t {
248 compressionLevel: level,
249 notificationLevel: notifications,
250 dictID: dict_id,
251 },
252 };
253
254 let mut samples_len = 0;
255
256 // Figure out total size of input samples. A side-effect is all elements are
257 // validated to be PyBytes.
258 for sample in samples.iter() {
259 let bytes = sample
260 .downcast::<PyBytes>()
261 .or_else(|_| Err(PyValueError::new_err("samples must be bytes")))?;
262
263 samples_len += bytes.as_bytes().len();
264 }
265
266 let mut samples_buffer: Vec<u8> = Vec::with_capacity(samples_len);
267 let mut sample_sizes: Vec<libc::size_t> = Vec::with_capacity(samples.len());
268
269 for sample in samples.iter() {
270 let bytes = sample.downcast::<PyBytes>()?;
271 let data = bytes.as_bytes();
272 sample_sizes.push(data.len());
273 samples_buffer.extend_from_slice(data);
274 }
275
276 let mut dict_data: Vec<u8> = Vec::with_capacity(dict_size);
277
278 train_dictionary_fastcover(&mut dict_data, &samples_buffer, &sample_sizes, &params)
279 .map_err(|msg| ZstdError::new_err(format!("cannot train dict: {}", msg)))?;
280
281 Ok(ZstdCompressionDict {
282 content_type: zstd_sys::ZSTD_dictContentType_e::ZSTD_dct_fullDict,
283 k: params.k,
284 d: params.d,
285 data: dict_data,
286 cdict: None,
287 ddict: None,
288 })
289 }
290
291 pub(crate) fn init_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
292 module.add_class::<ZstdCompressionDict>()?;
293 module.add_function(wrap_pyfunction!(train_dictionary, module)?)?;
294
295 Ok(())
296 }