Debian Codegraph @

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