Debian Codegraph @

contrib/python-zstandard/rust-ext/src/compression_reader.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::{
14 buffer::PyBuffer,
15 exceptions::{PyOSError, PyValueError},
16 prelude::*,
17 types::{PyBytes, PyList},
18 },
19 std::sync::Arc,
20 };
21
22 #[pyclass(module = "zstandard.backend_rust")]
23 pub struct ZstdCompressionReader {
24 cctx: Arc<CCtx<'static>>,
25 source: Box<dyn InBufferSource + Send>,
26 closefd: bool,
27 closed: bool,
28 entered: bool,
29 bytes_compressed: usize,
30 finished_output: bool,
31 }
32
33 impl ZstdCompressionReader {
34 pub fn new(
35 py: Python,
36 cctx: Arc<CCtx<'static>>,
37 reader: &Bound<'_, PyAny>,
38 size: u64,
39 read_size: usize,
40 closefd: bool,
41 ) -> PyResult<Self> {
42 let source = make_in_buffer_source(py, reader, read_size)?;
43
44 let size = match source.source_size() {
45 Some(size) => size as _,
46 None => size,
47 };
48
49 cctx.set_pledged_source_size(size).or_else(|msg| {
50 Err(ZstdError::new_err(format!(
51 "error setting source size: {}",
52 msg
53 )))
54 })?;
55
56 Ok(Self {
57 cctx,
58 source,
59 closefd,
60 closed: false,
61 entered: false,
62 bytes_compressed: 0,
63 finished_output: false,
64 })
65 }
66 }
67
68 impl ZstdCompressionReader {
69 fn compress_into_buffer(
70 &mut self,
71 py: Python,
72 out_buffer: &mut zstd_sys::ZSTD_outBuffer,
73 ) -> PyResult<bool> {
74 if let Some(mut in_buffer) = self.source.input_buffer(py)? {
75 let old_in_pos = in_buffer.pos;
76 let old_out_pos = out_buffer.pos;
77
78 self.cctx
79 .compress_buffers(
80 out_buffer,
81 &mut in_buffer,
82 zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
83 )
84 .map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
85
86 self.bytes_compressed += out_buffer.pos - old_out_pos;
87 self.source.record_bytes_read(in_buffer.pos - old_in_pos);
88
89 Ok(out_buffer.pos > 0 && out_buffer.pos == out_buffer.size)
90 } else {
91 Ok(false)
92 }
93 }
94
95 fn compress_into_vec(&mut self, py: Python, dest_buffer: &mut Vec<u8>) -> PyResult<bool> {
96 let mut out_buffer = zstd_sys::ZSTD_outBuffer {
97 dst: dest_buffer.as_mut_ptr() as *mut _,
98 size: dest_buffer.capacity(),
99 pos: dest_buffer.len(),
100 };
101
102 let res = self.compress_into_buffer(py, &mut out_buffer)?;
103
104 unsafe {
105 dest_buffer.set_len(out_buffer.pos);
106 }
107
108 Ok(res)
109 }
110 }
111
112 #[pymethods]
113 impl ZstdCompressionReader {
114 // PyIterProtocol.
115
116 fn __iter__(slf: PyRef<Self>) -> PyResult<()> {
117 let py = slf.py();
118 let io = py.import_bound("io")?;
119 let exc = io.getattr("UnsupportedOperation")?;
120
121 Err(PyErr::from_value_bound(exc))
122 }
123
124 fn __next__(slf: PyRef<Self>) -> PyResult<Option<()>> {
125 let py = slf.py();
126 let io = py.import_bound("io")?;
127 let exc = io.getattr("UnsupportedOperation")?;
128
129 Err(PyErr::from_value_bound(exc))
130 }
131
132 fn __enter__<'p>(mut slf: PyRefMut<'p, Self>, _py: Python<'p>) -> PyResult<PyRefMut<'p, Self>> {
133 if slf.entered {
134 Err(PyValueError::new_err("cannot __enter__ multiple times"))
135 } else if slf.closed {
136 Err(PyValueError::new_err("stream is closed"))
137 } else {
138 slf.entered = true;
139 Ok(slf)
140 }
141 }
142
143 fn __exit__<'p>(
144 mut slf: PyRefMut<'p, Self>,
145 py: Python<'p>,
146 _exc_type: PyObject,
147 _exc_value: PyObject,
148 _exc_tb: PyObject,
149 ) -> PyResult<bool> {
150 slf.entered = false;
151 slf.close(py)?;
152
153 // TODO release cctx and reader?
154
155 Ok(false)
156 }
157
158 fn readable(&self) -> bool {
159 true
160 }
161
162 fn writable(&self) -> bool {
163 false
164 }
165
166 fn seekable(&self) -> bool {
167 false
168 }
169
170 fn readline(&self, py: Python) -> PyResult<()> {
171 let io = py.import_bound("io")?;
172 let exc = io.getattr("UnsupportedOperation")?;
173
174 Err(PyErr::from_value_bound(exc))
175 }
176
177 #[pyo3(signature = (hint=None))]
178 #[allow(unused_variables)]
179 fn readlines(&self, py: Python, hint: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
180 let io = py.import_bound("io")?;
181 let exc = io.getattr("UnsupportedOperation")?;
182
183 Err(PyErr::from_value_bound(exc))
184 }
185
186 fn write(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> {
187 Err(PyOSError::new_err("stream is not writable"))
188 }
189
190 fn writelines(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> {
191 Err(PyOSError::new_err("stream is not writable"))
192 }
193
194 fn isatty(&self) -> bool {
195 false
196 }
197
198 fn flush(&self) -> PyResult<()> {
199 Ok(())
200 }
201
202 fn close(&mut self, py: Python) -> PyResult<()> {
203 if self.closed {
204 return Ok(());
205 }
206
207 self.closed = true;
208
209 if let Ok(close) = self.source.source_object().getattr(py, "close") {
210 if self.closefd {
211 close.call0(py)?;
212 }
213 }
214
215 Ok(())
216 }
217
218 #[getter]
219 fn closed(&self) -> bool {
220 self.closed
221 }
222
223 fn tell(&self) -> usize {
224 self.bytes_compressed
225 }
226
227 fn readall<'p>(&mut self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
228 let chunks = PyList::empty_bound(py);
229
230 loop {
231 let chunk = self.read(py, 1048576)?;
232
233 if chunk.len()? == 0 {
234 break;
235 }
236
237 chunks.append(chunk)?;
238 }
239
240 let empty = PyBytes::new_bound(py, &[]);
241
242 empty.call_method1("join", (chunks,))
243 }
244
245 #[pyo3(signature = (size=-1))]
246 fn read<'p>(&mut self, py: Python<'p>, size: isize) -> PyResult<Bound<'p, PyAny>> {
247 if self.closed {
248 return Err(PyValueError::new_err("stream is closed"));
249 }
250
251 if size < -1 {
252 return Err(PyValueError::new_err(
253 "cannot read negative amounts less than -1",
254 ));
255 }
256
257 if size == -1 {
258 return self.readall(py);
259 }
260
261 if self.finished_output || size == 0 {
262 return Ok(PyBytes::new_bound(py, &[]).into_any());
263 }
264
265 let mut dest_buffer: Vec<u8> = Vec::with_capacity(size as _);
266
267 while !self.source.finished() {
268 // If the output buffer is full, return its content.
269 if self.compress_into_vec(py, &mut dest_buffer)? {
270 // TODO avoid buffer copy.
271 return Ok(PyBytes::new_bound(py, &dest_buffer).into_any());
272 }
273 // Else continue to read new input into the compressor.
274 }
275
276 // EOF.
277 let old_pos = dest_buffer.len();
278
279 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
280 src: std::ptr::null_mut(),
281 size: 0,
282 pos: 0,
283 };
284
285 let zresult = self
286 .cctx
287 .compress_into_vec(
288 &mut dest_buffer,
289 &mut in_buffer,
290 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
291 )
292 .map_err(|msg| {
293 ZstdError::new_err(format!("error ending compression stream: {}", msg))
294 })?;
295
296 self.bytes_compressed += dest_buffer.len() - old_pos;
297
298 if zresult == 0 {
299 self.finished_output = true;
300 }
301
302 // TODO avoid buffer copy.
303 Ok(PyBytes::new_bound(py, &dest_buffer).into_any())
304 }
305
306 #[pyo3(signature = (size=-1))]
307 fn read1<'p>(&mut self, py: Python<'p>, size: isize) -> PyResult<Bound<'p, PyAny>> {
308 if self.closed {
309 return Err(PyValueError::new_err("stream is closed"));
310 }
311
312 if size < -1 {
313 return Err(PyValueError::new_err(
314 "cannot read negative amounts less than -1",
315 ));
316 }
317
318 if self.finished_output || size == 0 {
319 return Ok(PyBytes::new_bound(py, &[]).into_any());
320 }
321
322 // -1 returns arbitrary number of bytes.
323 let size = if size == -1 {
324 zstd_safe::CCtx::out_size()
325 } else {
326 size as _
327 };
328
329 let mut dest_buffer: Vec<u8> = Vec::with_capacity(size);
330
331 // read1() dictates that we can perform at most 1 call to the
332 // underlying stream to get input. However, we can't satisfy this
333 // restriction with compression because not all input generates output.
334 // It is possible to perform a block flush in order to ensure output.
335 // But this may not be desirable behavior. So we allow multiple read()
336 // to the underlying stream. But unlike our read(), we stop once we
337 // have any output.
338
339 // Read data until we exhaust input or have output data.
340 while !self.source.finished() && dest_buffer.is_empty() {
341 self.compress_into_vec(py, &mut dest_buffer)?;
342 }
343
344 // We return immediately if:
345 // a) output buffer is full
346 // b) output buffer has data and input isn't exhausted.
347 if dest_buffer.len() == dest_buffer.capacity()
348 || (!dest_buffer.is_empty() && !self.source.finished())
349 {
350 // TODO avoid buffer copy.
351 return Ok(PyBytes::new_bound(py, &dest_buffer).into_any());
352 }
353
354 // Input must be exhausted. Finish the compression stream.
355 let old_pos = dest_buffer.len();
356
357 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
358 src: std::ptr::null_mut(),
359 size: 0,
360 pos: 0,
361 };
362
363 let zresult = self
364 .cctx
365 .compress_into_vec(
366 &mut dest_buffer,
367 &mut in_buffer,
368 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
369 )
370 .map_err(|msg| {
371 ZstdError::new_err(format!("error ending compression stream: {}", msg))
372 })?;
373
374 self.bytes_compressed += dest_buffer.len() - old_pos;
375
376 if zresult == 0 {
377 self.finished_output = true;
378 }
379
380 // TODO avoid buffer copy
381 Ok(PyBytes::new_bound(py, &dest_buffer).into_any())
382 }
383
384 fn readinto(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> {
385 if buffer.readonly() {
386 return Err(PyValueError::new_err("buffer is not writable"));
387 }
388
389 if self.closed {
390 return Err(PyValueError::new_err("stream is closed"));
391 }
392
393 if self.finished_output {
394 return Ok(0);
395 }
396
397 let mut out_buffer = zstd_sys::ZSTD_outBuffer {
398 dst: buffer.buf_ptr(),
399 size: buffer.len_bytes(),
400 pos: 0,
401 };
402
403 while !self.source.finished() {
404 if self.compress_into_buffer(py, &mut out_buffer)? {
405 return Ok(out_buffer.pos);
406 }
407 }
408
409 // EOF.
410 let old_pos = out_buffer.pos;
411
412 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
413 src: std::ptr::null_mut(),
414 size: 0,
415 pos: 0,
416 };
417
418 let zresult = self
419 .cctx
420 .compress_buffers(
421 &mut out_buffer,
422 &mut in_buffer,
423 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
424 )
425 .map_err(|msg| {
426 ZstdError::new_err(format!("error ending compression stream: {}", msg))
427 })?;
428
429 self.bytes_compressed += out_buffer.pos - old_pos;
430
431 if zresult == 0 {
432 self.finished_output = true;
433 }
434
435 Ok(out_buffer.pos)
436 }
437
438 fn readinto1(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> {
439 if buffer.readonly() {
440 return Err(PyValueError::new_err("buffer is not writable"));
441 }
442
443 if self.closed {
444 return Err(PyValueError::new_err("stream is closed"));
445 }
446
447 if self.finished_output {
448 return Ok(0);
449 }
450
451 let mut out_buffer = zstd_sys::ZSTD_outBuffer {
452 dst: buffer.buf_ptr(),
453 size: buffer.len_bytes(),
454 pos: 0,
455 };
456
457 // Read until we get output.
458 while out_buffer.pos == 0 && !self.source.finished() {
459 self.compress_into_buffer(py, &mut out_buffer)?;
460 }
461
462 // If we still have input, return immediately.
463 if !self.source.finished() {
464 return Ok(out_buffer.pos);
465 }
466
467 // EOF.
468 let old_pos = out_buffer.pos;
469
470 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
471 src: std::ptr::null_mut(),
472 size: 0,
473 pos: 0,
474 };
475
476 let zresult = self
477 .cctx
478 .compress_buffers(
479 &mut out_buffer,
480 &mut in_buffer,
481 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
482 )
483 .map_err(|msg| {
484 ZstdError::new_err(format!("error ending compression stream: {}", msg))
485 })?;
486
487 self.bytes_compressed += out_buffer.pos - old_pos;
488
489 if zresult == 0 {
490 self.finished_output = true;
491 }
492
493 Ok(out_buffer.pos)
494 }
495 }