Debian Codegraph @

contrib/python-zstandard/rust-ext/src/compressionobj.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 constants::{COMPRESSOBJ_FLUSH_BLOCK, COMPRESSOBJ_FLUSH_FINISH},
10 zstd_safe::CCtx,
11 ZstdError,
12 },
13 pyo3::{buffer::PyBuffer, exceptions::PyValueError, prelude::*, types::PyBytes},
14 std::sync::Arc,
15 };
16
17 #[pyclass(module = "zstandard.backend_rust")]
18 pub struct ZstdCompressionObj {
19 cctx: Arc<CCtx<'static>>,
20 finished: bool,
21 }
22
23 impl ZstdCompressionObj {
24 pub fn new(cctx: Arc<CCtx<'static>>) -> PyResult<Self> {
25 Ok(ZstdCompressionObj {
26 cctx,
27 finished: false,
28 })
29 }
30 }
31
32 #[pymethods]
33 impl ZstdCompressionObj {
34 fn compress<'p>(&self, py: Python<'p>, buffer: PyBuffer<u8>) -> PyResult<Bound<'p, PyBytes>> {
35 if self.finished {
36 return Err(ZstdError::new_err(
37 "cannot call compress() after compressor finished",
38 ));
39 }
40
41 let mut source = unsafe {
42 std::slice::from_raw_parts::<u8>(buffer.buf_ptr() as *const _, buffer.len_bytes())
43 };
44
45 // TODO consider collecting chunks and joining
46 // TODO try to use zero copy into return value.
47 let mut compressed = Vec::new();
48 let write_size = zstd_safe::CCtx::out_size();
49
50 let cctx = &self.cctx;
51 while !source.is_empty() {
52 let result = py
53 .allow_threads(|| {
54 cctx.compress_chunk(
55 source,
56 zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
57 write_size,
58 )
59 })
60 .or_else(|msg| Err(ZstdError::new_err(format!("zstd compress error: {}", msg))))?;
61
62 compressed.extend(result.0);
63 source = result.1;
64 }
65
66 Ok(PyBytes::new_bound(py, &compressed))
67 }
68
69 fn flush<'p>(
70 &mut self,
71 py: Python<'p>,
72 flush_mode: Option<i32>,
73 ) -> PyResult<Bound<'p, PyBytes>> {
74 let flush_mode = if let Some(flush_mode) = flush_mode {
75 match flush_mode {
76 COMPRESSOBJ_FLUSH_FINISH => Ok(zstd_sys::ZSTD_EndDirective::ZSTD_e_end),
77 COMPRESSOBJ_FLUSH_BLOCK => Ok(zstd_sys::ZSTD_EndDirective::ZSTD_e_flush),
78 _ => Err(PyValueError::new_err("flush mode not recognized")),
79 }
80 } else {
81 Ok(zstd_sys::ZSTD_EndDirective::ZSTD_e_end)
82 }?;
83
84 if self.finished {
85 return Err(ZstdError::new_err("compressor object already finished"));
86 }
87
88 if flush_mode == zstd_sys::ZSTD_EndDirective::ZSTD_e_end {
89 self.finished = true;
90 }
91
92 let write_size = zstd_safe::CCtx::out_size();
93 let cctx = &self.cctx;
94
95 // TODO avoid extra buffer copy.
96 let mut result = Vec::new();
97
98 loop {
99 let (chunk, _, call_again) = py
100 .allow_threads(|| cctx.compress_chunk(&[], flush_mode, write_size))
101 .or_else(|msg| {
102 Err(ZstdError::new_err(format!(
103 "error ending compression stream: {}",
104 msg
105 )))
106 })?;
107
108 result.extend(&chunk);
109
110 if !call_again {
111 return Ok(PyBytes::new_bound(py, &result));
112 }
113 }
114 }
115 }