Debian Codegraph @

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