Debian Codegraph @

contrib/python-zstandard/rust-ext/src/compression_parameters.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::ZstdError,
9 libc::c_int,
10 pyo3::{
11 exceptions::{PyMemoryError, PyTypeError, PyValueError},
12 prelude::*,
13 types::{PyDict, PyTuple, PyType},
14 },
15 std::marker::PhantomData,
16 };
17
18 /// Safe wrapper for ZSTD_CCtx_params instances.
19 pub struct CCtxParams<'a>(*mut zstd_sys::ZSTD_CCtx_params, PhantomData<&'a ()>);
20
21 impl<'a> Drop for CCtxParams<'a> {
22 fn drop(&mut self) {
23 unsafe {
24 zstd_sys::ZSTD_freeCCtxParams(self.0);
25 }
26 }
27 }
28
29 unsafe impl<'a> Send for CCtxParams<'a> {}
30
31 unsafe impl<'a> Sync for CCtxParams<'a> {}
32
33 impl<'a> CCtxParams<'a> {
34 pub(crate) unsafe fn get_raw_ptr(&self) -> *mut zstd_sys::ZSTD_CCtx_params {
35 self.0
36 }
37 }
38
39 impl<'a> CCtxParams<'a> {
40 pub fn create() -> Result<Self, PyErr> {
41 let params = unsafe { zstd_sys::ZSTD_createCCtxParams() };
42 if params.is_null() {
43 return Err(PyMemoryError::new_err("unable to create ZSTD_CCtx_params"));
44 }
45 Ok(CCtxParams(params, PhantomData))
46 }
47
48 pub fn set_parameter(&self, param: zstd_sys::ZSTD_cParameter, value: i32) -> PyResult<()> {
49 let zresult = unsafe { zstd_sys::ZSTD_CCtxParams_setParameter(self.0, param, value) };
50 if unsafe { zstd_sys::ZSTD_isError(zresult) } != 0 {
51 Err(ZstdError::new_err(format!(
52 "unable to set compression context parameter: {}",
53 zstd_safe::get_error_name(zresult)
54 )))
55 } else {
56 Ok(())
57 }
58 }
59
60 fn apply_compression_parameter(
61 &self,
62 py: Python,
63 params: &Py<ZstdCompressionParameters>,
64 param: zstd_sys::ZSTD_cParameter,
65 ) -> PyResult<()> {
66 let value = params.borrow(py).get_parameter(param)?;
67 self.set_parameter(param, value)
68 }
69
70 pub fn apply_compression_parameters(
71 &self,
72 py: Python,
73 params: &Py<ZstdCompressionParameters>,
74 ) -> PyResult<()> {
75 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers)?;
76 // ZSTD_c_format.
77 self.apply_compression_parameter(
78 py,
79 &params,
80 zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam2,
81 )?;
82 self.apply_compression_parameter(
83 py,
84 &params,
85 zstd_sys::ZSTD_cParameter::ZSTD_c_compressionLevel,
86 )?;
87 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_windowLog)?;
88 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_hashLog)?;
89 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_chainLog)?;
90 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_searchLog)?;
91 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_minMatch)?;
92 self.apply_compression_parameter(
93 py,
94 &params,
95 zstd_sys::ZSTD_cParameter::ZSTD_c_targetLength,
96 )?;
97 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_strategy)?;
98 self.apply_compression_parameter(
99 py,
100 &params,
101 zstd_sys::ZSTD_cParameter::ZSTD_c_contentSizeFlag,
102 )?;
103 self.apply_compression_parameter(
104 py,
105 &params,
106 zstd_sys::ZSTD_cParameter::ZSTD_c_checksumFlag,
107 )?;
108 self.apply_compression_parameter(
109 py,
110 &params,
111 zstd_sys::ZSTD_cParameter::ZSTD_c_dictIDFlag,
112 )?;
113 self.apply_compression_parameter(py, &params, zstd_sys::ZSTD_cParameter::ZSTD_c_jobSize)?;
114 self.apply_compression_parameter(
115 py,
116 &params,
117 zstd_sys::ZSTD_cParameter::ZSTD_c_overlapLog,
118 )?;
119 // ZSTD_c_forceMaxWindow
120 self.apply_compression_parameter(
121 py,
122 &params,
123 zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam3,
124 )?;
125 self.apply_compression_parameter(
126 py,
127 &params,
128 zstd_sys::ZSTD_cParameter::ZSTD_c_overlapLog,
129 )?;
130 self.apply_compression_parameter(
131 py,
132 &params,
133 zstd_sys::ZSTD_cParameter::ZSTD_c_enableLongDistanceMatching,
134 )?;
135 self.apply_compression_parameter(
136 py,
137 &params,
138 zstd_sys::ZSTD_cParameter::ZSTD_c_ldmHashLog,
139 )?;
140 self.apply_compression_parameter(
141 py,
142 &params,
143 zstd_sys::ZSTD_cParameter::ZSTD_c_ldmMinMatch,
144 )?;
145 self.apply_compression_parameter(
146 py,
147 &params,
148 zstd_sys::ZSTD_cParameter::ZSTD_c_ldmBucketSizeLog,
149 )?;
150 self.apply_compression_parameter(
151 py,
152 &params,
153 zstd_sys::ZSTD_cParameter::ZSTD_c_ldmHashRateLog,
154 )?;
155
156 Ok(())
157 }
158 }
159
160 /// Resolve the value of a compression context parameter.
161 pub(crate) fn get_cctx_parameter(
162 params: *mut zstd_sys::ZSTD_CCtx_params,
163 param: zstd_sys::ZSTD_cParameter,
164 ) -> Result<libc::c_int, PyErr> {
165 let mut value: libc::c_int = 0;
166
167 let zresult =
168 unsafe { zstd_sys::ZSTD_CCtxParams_getParameter(params, param, &mut value as *mut _) };
169
170 if unsafe { zstd_sys::ZSTD_isError(zresult) } != 0 {
171 Err(ZstdError::new_err(format!(
172 "unable to retrieve parameter: {}",
173 zstd_safe::get_error_name(zresult)
174 )))
175 } else {
176 Ok(value)
177 }
178 }
179
180 // Surely there is a better way...
181 pub(crate) fn int_to_strategy(value: u32) -> Result<zstd_sys::ZSTD_strategy, PyErr> {
182 if zstd_sys::ZSTD_strategy::ZSTD_fast as u32 == value {
183 Ok(zstd_sys::ZSTD_strategy::ZSTD_fast)
184 } else if zstd_sys::ZSTD_strategy::ZSTD_dfast as u32 == value {
185 Ok(zstd_sys::ZSTD_strategy::ZSTD_dfast)
186 } else if zstd_sys::ZSTD_strategy::ZSTD_greedy as u32 == value {
187 Ok(zstd_sys::ZSTD_strategy::ZSTD_greedy)
188 } else if zstd_sys::ZSTD_strategy::ZSTD_lazy as u32 == value {
189 Ok(zstd_sys::ZSTD_strategy::ZSTD_lazy)
190 } else if zstd_sys::ZSTD_strategy::ZSTD_lazy2 as u32 == value {
191 Ok(zstd_sys::ZSTD_strategy::ZSTD_lazy2)
192 } else if zstd_sys::ZSTD_strategy::ZSTD_btlazy2 as u32 == value {
193 Ok(zstd_sys::ZSTD_strategy::ZSTD_btlazy2)
194 } else if zstd_sys::ZSTD_strategy::ZSTD_btopt as u32 == value {
195 Ok(zstd_sys::ZSTD_strategy::ZSTD_btopt)
196 } else if zstd_sys::ZSTD_strategy::ZSTD_btultra as u32 == value {
197 Ok(zstd_sys::ZSTD_strategy::ZSTD_btultra)
198 } else if zstd_sys::ZSTD_strategy::ZSTD_btultra2 as u32 == value {
199 Ok(zstd_sys::ZSTD_strategy::ZSTD_btultra2)
200 } else {
201 Err(PyValueError::new_err("unknown compression strategy"))
202 }
203 }
204
205 #[pyclass(module = "zstandard.backend_rust")]
206 pub struct ZstdCompressionParameters {
207 pub(crate) params: *mut zstd_sys::ZSTD_CCtx_params,
208 }
209
210 impl Drop for ZstdCompressionParameters {
211 fn drop(&mut self) {
212 unsafe {
213 zstd_sys::ZSTD_freeCCtxParams(self.params);
214 }
215 }
216 }
217
218 unsafe impl Send for ZstdCompressionParameters {}
219
220 impl ZstdCompressionParameters {
221 pub(crate) fn get_parameter(&self, param: zstd_sys::ZSTD_cParameter) -> PyResult<c_int> {
222 let mut value: c_int = 0;
223
224 let zresult = unsafe {
225 zstd_sys::ZSTD_CCtxParams_getParameter(self.params, param, &mut value as *mut _)
226 };
227
228 if unsafe { zstd_sys::ZSTD_isError(zresult) } != 0 {
229 return Err(ZstdError::new_err(format!(
230 "unable to retrieve parameter: {}",
231 zstd_safe::get_error_name(zresult)
232 )));
233 }
234
235 Ok(value)
236 }
237
238 fn set_parameter(&self, param: zstd_sys::ZSTD_cParameter, value: i32) -> PyResult<()> {
239 let zresult = unsafe { zstd_sys::ZSTD_CCtxParams_setParameter(self.params, param, value) };
240
241 if unsafe { zstd_sys::ZSTD_isError(zresult) } != 0 {
242 return Err(ZstdError::new_err(format!(
243 "unable to set compression context parameter: {}",
244 zstd_safe::get_error_name(zresult)
245 )));
246 }
247
248 Ok(())
249 }
250
251 /// Set parameters from a dictionary of options.
252 fn set_parameters(&self, kwargs: &Bound<'_, PyDict>) -> PyResult<()> {
253 unsafe {
254 zstd_sys::ZSTD_CCtxParams_reset(self.params);
255 }
256
257 let mut format = 0;
258 let mut compression_level = 0;
259 let mut window_log = 0;
260 let mut hash_log = 0;
261 let mut chain_log = 0;
262 let mut search_log = 0;
263 let mut min_match = 0;
264 let mut target_length = 0;
265 let mut strategy = -1;
266 let mut write_content_size = 1;
267 let mut write_checksum = 0;
268 let mut write_dict_id = 0;
269 let mut job_size = 0;
270 let mut overlap_log = -1;
271 let mut force_max_window = 0;
272 let mut enable_ldm = 0;
273 let mut ldm_hash_log = 0;
274 let mut ldm_min_match = 0;
275 let mut ldm_bucket_size_log = 0;
276 let mut ldm_hash_rate_log = -1;
277 let mut threads = 0;
278
279 for (key, value) in kwargs.iter() {
280 let key = key.extract::<String>()?;
281
282 match key.as_ref() {
283 "format" => format = value.extract::<_>()?,
284 "compression_level" => compression_level = value.extract::<_>()?,
285 "window_log" => window_log = value.extract::<_>()?,
286 "hash_log" => hash_log = value.extract::<_>()?,
287 "chain_log" => chain_log = value.extract::<_>()?,
288 "search_log" => search_log = value.extract::<_>()?,
289 "min_match" => min_match = value.extract::<_>()?,
290 "target_length" => target_length = value.extract::<_>()?,
291 "strategy" => strategy = value.extract::<_>()?,
292 "write_content_size" => write_content_size = value.extract::<_>()?,
293 "write_checksum" => write_checksum = value.extract::<_>()?,
294 "write_dict_id" => write_dict_id = value.extract::<_>()?,
295 "job_size" => job_size = value.extract::<_>()?,
296 "overlap_log" => overlap_log = value.extract::<_>()?,
297 "force_max_window" => force_max_window = value.extract::<_>()?,
298 "enable_ldm" => enable_ldm = value.extract::<_>()?,
299 "ldm_hash_log" => ldm_hash_log = value.extract::<_>()?,
300 "ldm_min_match" => ldm_min_match = value.extract::<_>()?,
301 "ldm_bucket_size_log" => ldm_bucket_size_log = value.extract::<_>()?,
302 "ldm_hash_rate_log" => ldm_hash_rate_log = value.extract::<_>()?,
303 "threads" => threads = value.extract::<_>()?,
304 key => {
305 return Err(PyTypeError::new_err(format!(
306 "'{}' is an invalid keyword argument",
307 key
308 )));
309 }
310 }
311 }
312
313 if threads < 0 {
314 threads = num_cpus::get() as _;
315 }
316
317 // We need to set ZSTD_c_nbWorkers before ZSTD_c_jobSize and ZSTD_c_overlapLog
318 // because setting ZSTD_c_nbWorkers resets the other parameters.
319 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers, threads)?;
320
321 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam2, format)?;
322 self.set_parameter(
323 zstd_sys::ZSTD_cParameter::ZSTD_c_compressionLevel,
324 compression_level,
325 )?;
326 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_windowLog, window_log)?;
327 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_hashLog, hash_log)?;
328 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_chainLog, chain_log)?;
329 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_searchLog, search_log)?;
330 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_minMatch, min_match)?;
331 self.set_parameter(
332 zstd_sys::ZSTD_cParameter::ZSTD_c_targetLength,
333 target_length,
334 )?;
335
336 if strategy == -1 {
337 strategy = 0;
338 }
339
340 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_strategy, strategy)?;
341 self.set_parameter(
342 zstd_sys::ZSTD_cParameter::ZSTD_c_contentSizeFlag,
343 write_content_size,
344 )?;
345 self.set_parameter(
346 zstd_sys::ZSTD_cParameter::ZSTD_c_checksumFlag,
347 write_checksum,
348 )?;
349 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_dictIDFlag, write_dict_id)?;
350 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_jobSize, job_size)?;
351
352 if overlap_log == -1 {
353 overlap_log = 0;
354 }
355
356 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_overlapLog, overlap_log)?;
357 self.set_parameter(
358 zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam3,
359 force_max_window,
360 )?;
361 self.set_parameter(
362 zstd_sys::ZSTD_cParameter::ZSTD_c_enableLongDistanceMatching,
363 enable_ldm,
364 )?;
365 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_ldmHashLog, ldm_hash_log)?;
366 self.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_ldmMinMatch, ldm_min_match)?;
367 self.set_parameter(
368 zstd_sys::ZSTD_cParameter::ZSTD_c_ldmBucketSizeLog,
369 ldm_bucket_size_log,
370 )?;
371
372 if ldm_hash_rate_log == -1 {
373 ldm_hash_rate_log = 0;
374 }
375
376 self.set_parameter(
377 zstd_sys::ZSTD_cParameter::ZSTD_c_ldmHashRateLog,
378 ldm_hash_rate_log,
379 )?;
380
381 Ok(())
382 }
383 }
384
385 #[pymethods]
386 impl ZstdCompressionParameters {
387 #[classmethod]
388 #[pyo3(signature = (* args, * * kwargs))]
389 fn from_level(
390 _cls: Bound<'_, PyType>,
391 py: Python,
392 args: &Bound<'_, PyTuple>,
393 kwargs: Option<&Bound<'_, PyDict>>,
394 ) -> PyResult<Self> {
395 if args.len() != 1 {
396 return Err(PyTypeError::new_err(format!(
397 "from_level() takes exactly 1 argument ({} given)",
398 args.len()
399 )));
400 }
401
402 let kwargs = if let Some(v) = kwargs {
403 v.copy()?
404 } else {
405 PyDict::new_bound(py)
406 };
407
408 let level = args.get_item(0)?.extract::<i32>()?;
409
410 let source_size = if let Some(value) = kwargs.get_item("source_size")? {
411 kwargs.del_item("source_size")?;
412 value.extract::<u64>()?
413 } else {
414 0
415 };
416
417 let dict_size = if let Some(value) = kwargs.get_item("dict_size")? {
418 kwargs.del_item("dict_size")?;
419 value.extract::<usize>()?
420 } else {
421 0
422 };
423
424 let compression_params =
425 unsafe { zstd_sys::ZSTD_getCParams(level, source_size, dict_size) };
426
427 if !kwargs.contains("window_log")? {
428 kwargs.set_item("window_log", compression_params.windowLog)?;
429 }
430 if !kwargs.contains("chain_log")? {
431 kwargs.set_item("chain_log", compression_params.chainLog)?;
432 }
433 if !kwargs.contains("hash_log")? {
434 kwargs.set_item("hash_log", compression_params.hashLog)?;
435 }
436 if !kwargs.contains("search_log")? {
437 kwargs.set_item("search_log", compression_params.searchLog)?;
438 }
439 if !kwargs.contains("min_match")? {
440 kwargs.set_item("min_match", compression_params.minMatch)?;
441 }
442 if !kwargs.contains("target_length")? {
443 kwargs.set_item("target_length", compression_params.targetLength)?;
444 }
445 if !kwargs.contains("strategy")? {
446 kwargs.set_item("strategy", compression_params.strategy as u32)?;
447 }
448
449 Self::new(py, &PyTuple::empty_bound(py), Some(&kwargs))
450 }
451
452 #[new]
453 #[pyo3(signature = (* _args, * * kwargs))]
454 fn new(
455 py: Python,
456 _args: &Bound<'_, PyTuple>,
457 kwargs: Option<&Bound<'_, PyDict>>,
458 ) -> PyResult<Self> {
459 let params = unsafe { zstd_sys::ZSTD_createCCtxParams() };
460 if params.is_null() {
461 return Err(PyMemoryError::new_err("unable to create ZSTD_CCtx_params"));
462 }
463
464 let instance = ZstdCompressionParameters { params };
465
466 let kwargs = if let Some(v) = kwargs {
467 v.copy()?
468 } else {
469 PyDict::new_bound(py)
470 };
471
472 instance.set_parameters(&kwargs)?;
473
474 Ok(instance)
475 }
476
477 #[getter]
478 fn format(&self) -> PyResult<c_int> {
479 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam2)
480 }
481
482 #[getter]
483 fn compression_level(&self) -> PyResult<c_int> {
484 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_compressionLevel)
485 }
486
487 #[getter]
488 fn window_log(&self) -> PyResult<c_int> {
489 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_windowLog)
490 }
491
492 #[getter]
493 fn hash_log(&self) -> PyResult<c_int> {
494 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_hashLog)
495 }
496
497 #[getter]
498 fn chain_log(&self) -> PyResult<c_int> {
499 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_chainLog)
500 }
501
502 #[getter]
503 fn search_log(&self) -> PyResult<c_int> {
504 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_searchLog)
505 }
506
507 #[getter]
508 fn min_match(&self) -> PyResult<c_int> {
509 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_minMatch)
510 }
511
512 #[getter]
513 fn target_length(&self) -> PyResult<c_int> {
514 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_targetLength)
515 }
516
517 #[getter]
518 fn strategy(&self) -> PyResult<c_int> {
519 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_strategy)
520 }
521
522 #[getter]
523 fn write_content_size(&self) -> PyResult<c_int> {
524 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_contentSizeFlag)
525 }
526
527 #[getter]
528 fn write_checksum(&self) -> PyResult<c_int> {
529 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_checksumFlag)
530 }
531
532 #[getter]
533 fn write_dict_id(&self) -> PyResult<c_int> {
534 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_dictIDFlag)
535 }
536
537 #[getter]
538 fn overlap_log(&self) -> PyResult<c_int> {
539 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_overlapLog)
540 }
541
542 #[getter]
543 fn force_max_window(&self) -> PyResult<c_int> {
544 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam3)
545 }
546
547 #[getter]
548 fn enable_ldm(&self) -> PyResult<c_int> {
549 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_enableLongDistanceMatching)
550 }
551
552 #[getter]
553 fn ldm_hash_log(&self) -> PyResult<c_int> {
554 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_ldmHashLog)
555 }
556
557 #[getter]
558 fn ldm_min_match(&self) -> PyResult<c_int> {
559 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_ldmMinMatch)
560 }
561
562 #[getter]
563 fn ldm_bucket_size_log(&self) -> PyResult<c_int> {
564 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_ldmBucketSizeLog)
565 }
566
567 #[getter]
568 fn ldm_hash_rate_log(&self) -> PyResult<c_int> {
569 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_ldmHashRateLog)
570 }
571
572 #[getter]
573 fn threads(&self) -> PyResult<c_int> {
574 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers)
575 }
576
577 #[getter]
578 fn job_size(&self) -> PyResult<c_int> {
579 self.get_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_jobSize)
580 }
581
582 fn estimated_compression_context_size(&self) -> PyResult<usize> {
583 let size = unsafe { zstd_sys::ZSTD_estimateCCtxSize_usingCCtxParams(self.params) };
584
585 Ok(size)
586 }
587 }
588
589 pub(crate) fn init_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
590 module.add_class::<ZstdCompressionParameters>()?;
591
592 Ok(())
593 }