Debian Codegraph @

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