Debian Codegraph @

contrib/python-zstandard/rust-ext/src/compressor.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 buffers::ZstdBufferWithSegmentsCollection,
10 compression_chunker::ZstdCompressionChunker,
11 compression_dict::ZstdCompressionDict,
12 compression_parameters::{CCtxParams, ZstdCompressionParameters},
13 compression_reader::ZstdCompressionReader,
14 compression_writer::ZstdCompressionWriter,
15 compressionobj::ZstdCompressionObj,
16 compressor_iterator::ZstdCompressorIterator,
17 compressor_multi::multi_compress_to_buffer,
18 zstd_safe::CCtx,
19 ZstdError,
20 },
21 pyo3::{buffer::PyBuffer, exceptions::PyValueError, prelude::*, types::PyBytes},
22 std::sync::Arc,
23 };
24
25 #[pyclass(module = "zstandard.backend_rust")]
26 struct ZstdCompressor {
27 _threads: i32,
28 dict: Option<Py<ZstdCompressionDict>>,
29 params: CCtxParams<'static>,
30 cctx: Arc<CCtx<'static>>,
31 }
32
33 impl ZstdCompressor {
34 pub(crate) fn setup_cctx(&self, py: Python) -> PyResult<()> {
35 self.cctx
36 .set_parameters(&self.params)
37 .or_else(|msg| Err(ZstdError::new_err(msg)))?;
38
39 if let Some(dict) = &self.dict {
40 dict.borrow(py).load_into_cctx(&self.cctx)?;
41 }
42
43 Ok(())
44 }
45 }
46
47 #[pymethods]
48 impl ZstdCompressor {
49 #[new]
50 #[pyo3(signature = (
51 level=3,
52 dict_data=None,
53 compression_params=None,
54 write_checksum=None,
55 write_content_size=None,
56 write_dict_id=None,
57 threads=0,
58 ))]
59 fn new(
60 py: Python,
61 level: i32,
62 dict_data: Option<Py<ZstdCompressionDict>>,
63 compression_params: Option<Py<ZstdCompressionParameters>>,
64 write_checksum: Option<bool>,
65 write_content_size: Option<bool>,
66 write_dict_id: Option<bool>,
67 threads: i32,
68 ) -> PyResult<Self> {
69 if level > zstd_safe::max_c_level() {
70 return Err(PyValueError::new_err(format!(
71 "level must be less than {}",
72 zstd_safe::max_c_level() as i32 + 1
73 )));
74 }
75
76 let threads = if threads < 0 {
77 num_cpus::get() as i32
78 } else {
79 threads
80 };
81
82 let cctx = Arc::new(CCtx::new().or_else(|msg| Err(PyErr::new::<ZstdError, _>(msg)))?);
83 let params = CCtxParams::create()?;
84
85 if let Some(compression_params) = &compression_params {
86 if write_checksum.is_some() {
87 return Err(PyValueError::new_err(
88 "cannot define compression_params and write_checksum",
89 ));
90 }
91 if write_content_size.is_some() {
92 return Err(PyValueError::new_err(
93 "cannot define compression_params and write_content_size",
94 ));
95 }
96 if write_dict_id.is_some() {
97 return Err(PyValueError::new_err(
98 "cannot define compression_params and write_dict_id",
99 ));
100 }
101 if threads != 0 {
102 return Err(PyValueError::new_err(
103 "cannot define compression_params and threads",
104 ));
105 }
106
107 params.apply_compression_parameters(py, compression_params)?;
108
109 // TODO set parameters from CompressionParameters
110 } else {
111 params.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_compressionLevel, level)?;
112 params.set_parameter(
113 zstd_sys::ZSTD_cParameter::ZSTD_c_contentSizeFlag,
114 if write_content_size.unwrap_or(true) {
115 1
116 } else {
117 0
118 },
119 )?;
120 params.set_parameter(
121 zstd_sys::ZSTD_cParameter::ZSTD_c_checksumFlag,
122 if write_checksum.unwrap_or(false) {
123 1
124 } else {
125 0
126 },
127 )?;
128 params.set_parameter(
129 zstd_sys::ZSTD_cParameter::ZSTD_c_dictIDFlag,
130 if write_dict_id.unwrap_or(true) { 1 } else { 0 },
131 )?;
132 if threads != 0 {
133 params.set_parameter(zstd_sys::ZSTD_cParameter::ZSTD_c_nbWorkers, threads)?;
134 }
135 }
136
137 let compressor = ZstdCompressor {
138 _threads: threads,
139 dict: dict_data,
140 params,
141 cctx,
142 };
143
144 compressor.setup_cctx(py)?;
145
146 Ok(compressor)
147 }
148
149 fn memory_size(&self) -> PyResult<usize> {
150 Ok(self.cctx.memory_size())
151 }
152
153 fn frame_progression(&self) -> PyResult<(usize, usize, usize)> {
154 let progression = self.cctx.get_frame_progression();
155
156 Ok((
157 progression.ingested as usize,
158 progression.consumed as usize,
159 progression.produced as usize,
160 ))
161 }
162
163 fn compress<'p>(&self, py: Python<'p>, buffer: PyBuffer<u8>) -> PyResult<Bound<'p, PyBytes>> {
164 let source: &[u8] =
165 unsafe { std::slice::from_raw_parts(buffer.buf_ptr() as *const _, buffer.len_bytes()) };
166
167 let cctx = &self.cctx;
168
169 // TODO implement 0 copy via Py_SIZE().
170 let data = py
171 .allow_threads(|| cctx.compress(source))
172 .or_else(|msg| Err(ZstdError::new_err(format!("cannot compress: {}", msg))))?;
173
174 Ok(PyBytes::new_bound(py, &data))
175 }
176
177 #[pyo3(signature = (size=None, chunk_size=None))]
178 fn chunker(
179 &self,
180 size: Option<u64>,
181 chunk_size: Option<usize>,
182 ) -> PyResult<ZstdCompressionChunker> {
183 self.cctx.reset();
184
185 let size = size.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN);
186 let chunk_size = chunk_size.unwrap_or_else(|| zstd_safe::CCtx::out_size());
187
188 self.cctx.set_pledged_source_size(size).or_else(|msg| {
189 Err(ZstdError::new_err(format!(
190 "error setting source size: {}",
191 msg
192 )))
193 })?;
194
195 ZstdCompressionChunker::new(self.cctx.clone(), chunk_size)
196 }
197
198 #[pyo3(signature = (size=None))]
199 fn compressobj(&self, size: Option<u64>) -> PyResult<ZstdCompressionObj> {
200 self.cctx.reset();
201
202 let size = if let Some(size) = size {
203 size
204 } else {
205 zstd_safe::CONTENTSIZE_UNKNOWN
206 };
207
208 self.cctx.set_pledged_source_size(size).or_else(|msg| {
209 Err(ZstdError::new_err(format!(
210 "error setting source size: {}",
211 msg
212 )))
213 })?;
214
215 ZstdCompressionObj::new(self.cctx.clone())
216 }
217
218 #[pyo3(signature = (ifh, ofh, size=None, read_size=None, write_size=None))]
219 fn copy_stream(
220 &self,
221 py: Python,
222 ifh: &Bound<'_, PyAny>,
223 ofh: &Bound<'_, PyAny>,
224 size: Option<u64>,
225 read_size: Option<usize>,
226 write_size: Option<usize>,
227 ) -> PyResult<(usize, usize)> {
228 let source_size = if let Some(source_size) = size {
229 source_size
230 } else {
231 zstd_safe::CONTENTSIZE_UNKNOWN
232 };
233
234 let read_size = read_size.unwrap_or_else(|| zstd_safe::CCtx::in_size());
235 let write_size = write_size.unwrap_or_else(|| zstd_safe::CCtx::in_size());
236
237 if !ifh.hasattr("read")? {
238 return Err(PyValueError::new_err(
239 "first argument must have a read() method",
240 ));
241 }
242 if !ofh.hasattr("write")? {
243 return Err(PyValueError::new_err(
244 "second argument must have a write() method",
245 ));
246 }
247
248 self.cctx.reset();
249 self.cctx
250 .set_pledged_source_size(source_size)
251 .or_else(|msg| {
252 Err(ZstdError::new_err(format!(
253 "error setting source size: {}",
254 msg
255 )))
256 })?;
257
258 let mut total_read = 0;
259 let mut total_write = 0;
260
261 loop {
262 // Try to read from source stream.
263 let read_object = ifh.call_method("read", (read_size,), None)?;
264
265 let read_bytes = read_object.downcast::<PyBytes>()?;
266 let read_data = read_bytes.as_bytes();
267
268 // If no data was read we are at EOF.
269 if read_data.len() == 0 {
270 break;
271 }
272
273 total_read += read_data.len();
274
275 // Send data to compressor.
276
277 let mut source = read_data;
278 let cctx = &self.cctx;
279
280 while !source.is_empty() {
281 let result = py
282 .allow_threads(|| {
283 cctx.compress_chunk(
284 source,
285 zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
286 write_size,
287 )
288 })
289 .or_else(|msg| {
290 Err(ZstdError::new_err(format!("zstd compress error: {}", msg)))
291 })?;
292
293 source = result.1;
294
295 let chunk = &result.0;
296
297 if !chunk.is_empty() {
298 // TODO avoid buffer copy.
299 let data = PyBytes::new_bound(py, chunk);
300 ofh.call_method("write", (data,), None)?;
301 total_write += chunk.len();
302 }
303 }
304 }
305
306 // We've finished reading. Now flush the compressor stream.
307 loop {
308 let result = self
309 .cctx
310 .compress_chunk(&[], zstd_sys::ZSTD_EndDirective::ZSTD_e_end, write_size)
311 .or_else(|msg| {
312 Err(ZstdError::new_err(format!(
313 "error ending compression stream: {}",
314 msg
315 )))
316 })?;
317
318 let chunk = &result.0;
319
320 if !chunk.is_empty() {
321 // TODO avoid buffer copy.
322 let data = PyBytes::new_bound(py, &chunk);
323 ofh.call_method("write", (data,), None)?;
324 total_write += chunk.len();
325 }
326
327 if !result.2 {
328 break;
329 }
330 }
331
332 Ok((total_read, total_write))
333 }
334
335 #[pyo3(signature = (data, threads=0))]
336 fn multi_compress_to_buffer(
337 &self,
338 py: Python,
339 data: &Bound<'_, PyAny>,
340 threads: isize,
341 ) -> PyResult<ZstdBufferWithSegmentsCollection> {
342 multi_compress_to_buffer(py, &self.params, &self.dict, data, threads)
343 }
344
345 #[pyo3(signature = (reader, size=None, read_size=None, write_size=None))]
346 fn read_to_iter(
347 &self,
348 py: Python,
349 reader: &Bound<'_, PyAny>,
350 size: Option<u64>,
351 read_size: Option<usize>,
352 write_size: Option<usize>,
353 ) -> PyResult<ZstdCompressorIterator> {
354 let size = size.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN);
355 let read_size = read_size.unwrap_or_else(|| zstd_safe::CCtx::in_size());
356 let write_size = write_size.unwrap_or_else(|| zstd_safe::CCtx::in_size());
357
358 self.cctx.reset();
359
360 ZstdCompressorIterator::new(py, self.cctx.clone(), reader, size, read_size, write_size)
361 }
362
363 #[pyo3(signature = (source, size=None, read_size=None, closefd=true))]
364 fn stream_reader(
365 &self,
366 py: Python,
367 source: &Bound<'_, PyAny>,
368 size: Option<u64>,
369 read_size: Option<usize>,
370 closefd: bool,
371 ) -> PyResult<ZstdCompressionReader> {
372 let size = size.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN);
373 let read_size = read_size.unwrap_or_else(|| zstd_safe::CCtx::in_size());
374
375 self.cctx.reset();
376
377 ZstdCompressionReader::new(py, self.cctx.clone(), source, size, read_size, closefd)
378 }
379
380 #[pyo3(signature = (writer, size=None, write_size=None, write_return_read=true, closefd=true))]
381 fn stream_writer(
382 &self,
383 py: Python,
384 writer: &Bound<'_, PyAny>,
385 size: Option<u64>,
386 write_size: Option<usize>,
387 write_return_read: bool,
388 closefd: bool,
389 ) -> PyResult<ZstdCompressionWriter> {
390 if !writer.hasattr("write")? {
391 return Err(PyValueError::new_err(
392 "must pass object with a write() method",
393 ));
394 }
395
396 self.cctx.reset();
397
398 let size = size.unwrap_or(zstd_sys::ZSTD_CONTENTSIZE_UNKNOWN as _);
399 let write_size = write_size.unwrap_or_else(|| unsafe { zstd_sys::ZSTD_CStreamOutSize() });
400
401 ZstdCompressionWriter::new(
402 py,
403 self.cctx.clone(),
404 writer,
405 size,
406 write_size,
407 write_return_read,
408 closefd,
409 )
410 }
411 }
412
413 pub(crate) fn init_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
414 module.add_class::<ZstdCompressor>()?;
415
416 Ok(())
417 }