Debian Codegraph @

contrib/python-zstandard/rust-ext/src/compression_chunker.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 exceptions::ZstdError,
10 stream::{make_in_buffer_source, InBufferSource},
11 zstd_safe::CCtx,
12 },
13 pyo3::{prelude::*, types::PyBytes},
14 std::sync::Arc,
15 };
16
17 #[pyclass(module = "zstandard.backend_rust")]
18 pub struct ZstdCompressionChunker {
19 cctx: Arc<CCtx<'static>>,
20 chunk_size: usize,
21 finished: bool,
22 iterator: Option<Py<ZstdCompressionChunkerIterator>>,
23 partial_buffer: Option<Vec<u8>>,
24 }
25
26 impl ZstdCompressionChunker {
27 pub fn new(cctx: Arc<CCtx<'static>>, chunk_size: usize) -> PyResult<Self> {
28 Ok(Self {
29 cctx,
30 chunk_size,
31 finished: false,
32 iterator: None,
33 partial_buffer: None,
34 })
35 }
36 }
37
38 impl ZstdCompressionChunker {
39 fn ensure_state(&mut self, py: Python) {
40 if let Some(it) = &self.iterator {
41 if it.borrow(py).finished {
42 if it.borrow(py).mode == IteratorMode::Finish {
43 self.finished = true;
44 }
45
46 if !it.borrow(py).dest_buffer.is_empty() {
47 // TODO can we avoid the memory copy?
48 // Vec.clone() won't preserve the capacity of the source.
49 // So we create a new Vec with desired capacity and copy to it.
50 // This is strictly better than a clone + resize.
51 let mut dest_buffer = Vec::with_capacity(self.chunk_size);
52 unsafe {
53 dest_buffer.set_len(it.borrow(py).dest_buffer.len());
54 }
55 dest_buffer.copy_from_slice(it.borrow(py).dest_buffer.as_slice());
56 self.partial_buffer = Some(dest_buffer);
57 }
58
59 self.iterator = None;
60 }
61 }
62 }
63
64 fn get_dest_buffer(&mut self) -> Vec<u8> {
65 self.partial_buffer
66 .take()
67 .unwrap_or_else(|| Vec::with_capacity(self.chunk_size))
68 }
69 }
70
71 #[pymethods]
72 impl ZstdCompressionChunker {
73 fn compress(
74 &mut self,
75 py: Python,
76 data: &Bound<'_, PyAny>,
77 ) -> PyResult<Py<ZstdCompressionChunkerIterator>> {
78 self.ensure_state(py);
79
80 if self.finished {
81 return Err(ZstdError::new_err(
82 "cannot call compress() after compression finished",
83 ));
84 }
85
86 let source = make_in_buffer_source(py, data, zstd_safe::CCtx::in_size())?;
87
88 let it = Py::new(
89 py,
90 ZstdCompressionChunkerIterator {
91 cctx: self.cctx.clone(),
92 source,
93 mode: IteratorMode::Normal,
94 dest_buffer: self.get_dest_buffer(),
95 finished: false,
96 },
97 )?;
98
99 self.iterator = Some(it.clone());
100
101 Ok(it)
102 }
103
104 fn flush<'p>(&mut self, py: Python<'p>) -> PyResult<Py<ZstdCompressionChunkerIterator>> {
105 self.ensure_state(py);
106
107 if self.finished {
108 return Err(ZstdError::new_err(
109 "cannot call flush() after compression finished",
110 ));
111 }
112
113 if self.iterator.is_some() {
114 return Err(ZstdError::new_err(
115 "cannot call flush() before consuming output from previous operation",
116 ));
117 }
118
119 let source =
120 make_in_buffer_source(py, &PyBytes::new_bound(py, &[]), zstd_safe::CCtx::in_size())?;
121
122 let it = Py::new(
123 py,
124 ZstdCompressionChunkerIterator {
125 cctx: self.cctx.clone(),
126 source,
127 mode: IteratorMode::Flush,
128 dest_buffer: self.get_dest_buffer(),
129 finished: false,
130 },
131 )?;
132
133 self.iterator = Some(it.clone());
134
135 Ok(it)
136 }
137
138 fn finish<'p>(&mut self, py: Python<'p>) -> PyResult<Py<ZstdCompressionChunkerIterator>> {
139 self.ensure_state(py);
140
141 if self.finished {
142 return Err(ZstdError::new_err(
143 "cannot call finish() after compression finished",
144 ));
145 }
146
147 if self.iterator.is_some() {
148 return Err(ZstdError::new_err(
149 "cannot call finish() before consuming output from previous operation",
150 ));
151 }
152
153 let source =
154 make_in_buffer_source(py, &PyBytes::new_bound(py, &[]), zstd_safe::CCtx::in_size())?;
155
156 let it = Py::new(
157 py,
158 ZstdCompressionChunkerIterator {
159 cctx: self.cctx.clone(),
160 source,
161 mode: IteratorMode::Finish,
162 dest_buffer: self.get_dest_buffer(),
163 finished: false,
164 },
165 )?;
166
167 self.iterator = Some(it.clone());
168
169 Ok(it)
170 }
171 }
172
173 #[derive(Debug, PartialEq)]
174 enum IteratorMode {
175 Normal,
176 Flush,
177 Finish,
178 }
179
180 #[pyclass(module = "zstandard.backend_rust")]
181 struct ZstdCompressionChunkerIterator {
182 cctx: Arc<CCtx<'static>>,
183 source: Box<dyn InBufferSource + Send>,
184 mode: IteratorMode,
185 dest_buffer: Vec<u8>,
186 finished: bool,
187 }
188
189 #[pymethods]
190 impl ZstdCompressionChunkerIterator {
191 // PyIterProtocol.
192
193 fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
194 slf
195 }
196
197 fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<PyObject>> {
198 if slf.finished {
199 return Ok(None);
200 }
201
202 let py = unsafe { Python::assume_gil_acquired() };
203
204 // Consume any data left in the input.
205 while let Some(mut in_buffer) = slf.source.input_buffer(py)? {
206 let old_pos = in_buffer.pos;
207
208 slf.cctx
209 .clone()
210 .compress_into_vec(
211 &mut slf.dest_buffer,
212 &mut in_buffer,
213 zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
214 )
215 .map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
216
217 slf.source.record_bytes_read(in_buffer.pos - old_pos);
218
219 // If we produced a full output chunk, emit it.
220 if slf.dest_buffer.len() == slf.dest_buffer.capacity() {
221 let chunk = PyBytes::new_bound(py, &slf.dest_buffer);
222 slf.dest_buffer.clear();
223
224 return Ok(Some(chunk.into_py(py)));
225 }
226
227 // Else continue to compress available input data.
228 continue;
229 }
230
231 // No more input data. A partial chunk may be in the destination
232 // buffer. If we're in normal compression mode, we're done. Otherwise
233 // if we're in flush or finish mode, we need to emit what data remains.
234
235 let flush_mode = match slf.mode {
236 IteratorMode::Normal => {
237 slf.finished = true;
238 return Ok(None);
239 }
240 IteratorMode::Flush => zstd_sys::ZSTD_EndDirective::ZSTD_e_flush,
241 IteratorMode::Finish => zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
242 };
243
244 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
245 src: std::ptr::null(),
246 size: 0,
247 pos: 0,
248 };
249
250 let zresult = slf
251 .cctx
252 .clone()
253 .compress_into_vec(&mut slf.dest_buffer, &mut in_buffer, flush_mode)
254 .map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
255
256 // When flushing or finishing, we always emit data in the output
257 // buffer. But the operation could fill the output buffer and not be
258 // finished.
259
260 // If we didn't emit anything to the output buffer, we must be finished.
261 // Update state and stop iteration.
262 if slf.dest_buffer.is_empty() {
263 slf.finished = true;
264 return Ok(None);
265 }
266
267 // If the flush or finish didn't fill the output buffer, we must
268 // be done.
269 // If compressor said operation is finished, we are also done.
270 if zresult == 0 || slf.dest_buffer.len() < slf.dest_buffer.capacity() {
271 slf.finished = true;
272 }
273
274 let chunk = PyBytes::new_bound(py, &slf.dest_buffer);
275 slf.dest_buffer.clear();
276
277 Ok(Some(chunk.into_py(py)))
278 }
279 }