Debian Codegraph @

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