Debian Codegraph @

contrib/python-zstandard/rust-ext/src/decompression_writer.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::{exceptions::ZstdError, zstd_safe::DCtx},
9 pyo3::{
10 buffer::PyBuffer,
11 exceptions::{PyOSError, PyValueError},
12 prelude::*,
13 types::PyBytes,
14 },
15 std::sync::Arc,
16 };
17
18 #[pyclass(module = "zstandard.backend_rust")]
19 pub struct ZstdDecompressionWriter {
20 dctx: Arc<DCtx<'static>>,
21 writer: PyObject,
22 write_size: usize,
23 write_return_read: bool,
24 closefd: bool,
25 entered: bool,
26 closing: bool,
27 closed: bool,
28 }
29
30 impl ZstdDecompressionWriter {
31 pub fn new(
32 py: Python,
33 dctx: Arc<DCtx<'static>>,
34 writer: &Bound<'_, PyAny>,
35 write_size: usize,
36 write_return_read: bool,
37 closefd: bool,
38 ) -> PyResult<Self> {
39 Ok(Self {
40 dctx,
41 writer: writer.into_py(py),
42 write_size,
43 write_return_read,
44 closefd,
45 entered: false,
46 closing: false,
47 closed: false,
48 })
49 }
50 }
51
52 #[pymethods]
53 impl ZstdDecompressionWriter {
54 // PyIterProtocol.
55
56 fn __iter__(slf: PyRef<Self>) -> PyResult<()> {
57 let py = slf.py();
58 let io = py.import_bound("io")?;
59 let exc = io.getattr("UnsupportedOperation")?;
60
61 Err(PyErr::from_value_bound(exc))
62 }
63
64 fn __next__(slf: PyRef<Self>) -> PyResult<Option<()>> {
65 let py = slf.py();
66 let io = py.import_bound("io")?;
67 let exc = io.getattr("UnsupportedOperation")?;
68
69 Err(PyErr::from_value_bound(exc))
70 }
71
72 fn __enter__<'p>(mut slf: PyRefMut<'p, Self>, _py: Python<'p>) -> PyResult<PyRefMut<'p, Self>> {
73 if slf.closed {
74 Err(PyValueError::new_err("stream is closed"))
75 } else if slf.entered {
76 Err(ZstdError::new_err("cannot __enter__ multiple times"))
77 } else {
78 slf.entered = true;
79 Ok(slf)
80 }
81 }
82
83 #[allow(unused_variables)]
84 fn __exit__<'p>(
85 mut slf: PyRefMut<'p, Self>,
86 py: Python<'p>,
87 exc_type: PyObject,
88 exc_value: PyObject,
89 exc_tb: PyObject,
90 ) -> PyResult<bool> {
91 slf.entered = false;
92 slf.close(py)?;
93
94 // TODO release cctx and writer?
95
96 Ok(false)
97 }
98
99 fn memory_size(&self) -> usize {
100 self.dctx.memory_size()
101 }
102
103 fn close(&mut self, py: Python) -> PyResult<()> {
104 if self.closed {
105 return Ok(());
106 }
107
108 self.closing = true;
109 let res = self.flush(py);
110 self.closing = false;
111 self.closed = true;
112
113 res?;
114
115 if let Ok(close) = self.writer.getattr(py, "close") {
116 if self.closefd {
117 close.call0(py)?;
118 }
119 }
120
121 Ok(())
122 }
123
124 #[getter]
125 fn closed(&self) -> bool {
126 self.closed
127 }
128
129 fn fileno(&self, py: Python) -> PyResult<PyObject> {
130 if let Ok(fileno) = self.writer.getattr(py, "fileno") {
131 fileno.call0(py)
132 } else {
133 Err(PyOSError::new_err(
134 "filenot not available on underlying writer",
135 ))
136 }
137 }
138
139 fn flush(&self, py: Python) -> PyResult<PyObject> {
140 if self.closed {
141 return Err(PyValueError::new_err("stream is closed"));
142 }
143
144 if let Ok(flush) = self.writer.getattr(py, "flush") {
145 if !self.closing {
146 return flush.call0(py);
147 }
148 }
149
150 Ok(py.None())
151 }
152
153 fn isatty(&self) -> bool {
154 false
155 }
156
157 fn readable(&self) -> bool {
158 false
159 }
160
161 #[pyo3(signature = (size=None))]
162 #[allow(unused_variables)]
163 fn readline(&self, py: Python, size: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
164 let io = py.import_bound("io")?;
165 let exc = io.getattr("UnsupportedOperation")?;
166
167 Err(PyErr::from_value_bound(exc))
168 }
169
170 #[pyo3(signature = (hint=None))]
171 #[allow(unused_variables)]
172 fn readlines(&self, py: Python, hint: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
173 let io = py.import_bound("io")?;
174 let exc = io.getattr("UnsupportedOperation")?;
175
176 Err(PyErr::from_value_bound(exc))
177 }
178
179 #[pyo3(signature = (offset, whence=None))]
180 #[allow(unused_variables)]
181 fn seek(&self, py: Python, offset: isize, whence: Option<i32>) -> PyResult<()> {
182 let io = py.import_bound("io")?;
183 let exc = io.getattr("UnsupportedOperation")?;
184
185 Err(PyErr::from_value_bound(exc))
186 }
187
188 fn seekable(&self) -> bool {
189 false
190 }
191
192 fn tell(&self, py: Python) -> PyResult<()> {
193 let io = py.import_bound("io")?;
194 let exc = io.getattr("UnsupportedOperation")?;
195
196 Err(PyErr::from_value_bound(exc))
197 }
198
199 #[pyo3(signature = (size=None))]
200 #[allow(unused_variables)]
201 fn truncate(&self, py: Python, size: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
202 let io = py.import_bound("io")?;
203 let exc = io.getattr("UnsupportedOperation")?;
204
205 Err(PyErr::from_value_bound(exc))
206 }
207
208 fn writable(&self) -> bool {
209 true
210 }
211
212 #[pyo3(signature = (lines))]
213 #[allow(unused_variables)]
214 fn writelines(&self, py: Python, lines: &Bound<'_, PyAny>) -> PyResult<()> {
215 let io = py.import_bound("io")?;
216 let exc = io.getattr("UnsupportedOperation")?;
217
218 Err(PyErr::from_value_bound(exc))
219 }
220
221 #[pyo3(signature = (size=None))]
222 #[allow(unused_variables)]
223 fn read(&self, py: Python, size: Option<usize>) -> PyResult<()> {
224 let io = py.import_bound("io")?;
225 let exc = io.getattr("UnsupportedOperation")?;
226
227 Err(PyErr::from_value_bound(exc))
228 }
229
230 fn readall(&self, py: Python) -> PyResult<()> {
231 let io = py.import_bound("io")?;
232 let exc = io.getattr("UnsupportedOperation")?;
233
234 Err(PyErr::from_value_bound(exc))
235 }
236
237 #[allow(unused_variables)]
238 fn readinto(&self, py: Python, buffer: &Bound<'_, PyAny>) -> PyResult<()> {
239 let io = py.import_bound("io")?;
240 let exc = io.getattr("UnsupportedOperation")?;
241
242 Err(PyErr::from_value_bound(exc))
243 }
244
245 #[pyo3(signature = (size=None))]
246 #[allow(unused_variables)]
247 fn read1(&self, py: Python, size: Option<usize>) -> PyResult<()> {
248 let io = py.import_bound("io")?;
249 let exc = io.getattr("UnsupportedOperation")?;
250
251 Err(PyErr::from_value_bound(exc))
252 }
253
254 #[allow(unused_variables)]
255 fn readinto1(&self, py: Python, buffer: &Bound<'_, PyAny>) -> PyResult<()> {
256 let io = py.import_bound("io")?;
257 let exc = io.getattr("UnsupportedOperation")?;
258
259 Err(PyErr::from_value_bound(exc))
260 }
261
262 fn write(&self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> {
263 if self.closed {
264 return Err(PyValueError::new_err("stream is closed"));
265 }
266
267 let mut total_write = 0;
268
269 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
270 src: buffer.buf_ptr(),
271 size: buffer.len_bytes(),
272 pos: 0,
273 };
274
275 let mut dest_buffer = Vec::with_capacity(self.write_size);
276
277 while in_buffer.pos < in_buffer.size {
278 self.dctx
279 .decompress_into_vec(&mut dest_buffer, &mut in_buffer)
280 .map_err(|msg| ZstdError::new_err(format!("zstd decompress error: {}", msg)))?;
281
282 if !dest_buffer.is_empty() {
283 // TODO avoid buffer copy.
284 let chunk = PyBytes::new_bound(py, &dest_buffer);
285 self.writer.call_method1(py, "write", (chunk,))?;
286 total_write += dest_buffer.len();
287 dest_buffer.clear();
288 }
289 }
290
291 if self.write_return_read {
292 Ok(in_buffer.pos)
293 } else {
294 Ok(total_write)
295 }
296 }
297 }