Debian Codegraph @

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