Debian Codegraph @

contrib/python-zstandard/rust-ext/src/decompressor_iterator.rs

raw
1 // Copyright (c) 2021-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::DCtx,
12 },
13 pyo3::{exceptions::PyValueError, prelude::*, types::PyBytes},
14 std::{cmp::min, sync::Arc},
15 };
16
17 #[pyclass(module = "zstandard.backend_rust")]
18 pub struct ZstdDecompressorIterator {
19 dctx: Arc<DCtx<'static>>,
20 source: Box<dyn InBufferSource + Send>,
21 write_size: usize,
22 finished_output: bool,
23 }
24
25 #[pymethods]
26 impl ZstdDecompressorIterator {
27 // PyIterProtocol.
28
29 fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
30 slf
31 }
32
33 fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<PyObject>> {
34 if slf.finished_output {
35 return Ok(None);
36 }
37
38 let py = unsafe { Python::assume_gil_acquired() };
39
40 let mut dest_buffer: Vec<u8> = Vec::with_capacity(slf.write_size);
41
42 // While input is available.
43 while let Some(mut in_buffer) = slf.source.input_buffer(py)? {
44 let old_pos = in_buffer.pos;
45
46 let zresult = slf
47 .dctx
48 .decompress_into_vec(&mut dest_buffer, &mut in_buffer)
49 .map_err(|msg| ZstdError::new_err(format!("zstd decompress error: {}", msg)))?;
50
51 slf.source.record_bytes_read(in_buffer.pos - old_pos);
52
53 if zresult == 0 {
54 slf.finished_output = true;
55 }
56
57 // Emit chunk if output buffer has data.
58 if !dest_buffer.is_empty() {
59 // TODO avoid buffer copy.
60 let chunk = PyBytes::new_bound(py, &dest_buffer);
61 return Ok(Some(chunk.into_py(py)));
62 }
63
64 // Repeat loop to collect more input data.
65 continue;
66 }
67
68 // Input is exhausted. Emit what we have or finish.
69 if !dest_buffer.is_empty() {
70 // TODO avoid buffer copy.
71 let chunk = PyBytes::new_bound(py, &dest_buffer);
72 Ok(Some(chunk.into_py(py)))
73 } else {
74 Ok(None)
75 }
76 }
77 }
78
79 impl ZstdDecompressorIterator {
80 pub fn new(
81 py: Python,
82 dctx: Arc<DCtx<'static>>,
83 reader: &Bound<'_, PyAny>,
84 read_size: usize,
85 write_size: usize,
86 skip_bytes: usize,
87 ) -> PyResult<Self> {
88 let mut source = make_in_buffer_source(py, reader, read_size)?;
89
90 let mut skip_bytes = skip_bytes;
91 while skip_bytes > 0 {
92 let in_buffer = source
93 .input_buffer(py)?
94 .ok_or_else(|| PyValueError::new_err("skip_bytes larger than first input chunk"))?;
95
96 let read = min(skip_bytes, in_buffer.size - in_buffer.pos);
97 source.record_bytes_read(read);
98 skip_bytes -= read;
99 }
100
101 Ok(Self {
102 dctx,
103 source,
104 write_size,
105 finished_output: false,
106 })
107 }
108 }