Debian Codegraph @

rust-ext/src/decompressionobj.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 prelude::*,
12 types::{PyBytes, PyList},
13 },
14 std::sync::Arc,
15 };
16
17 #[pyclass(module = "zstandard.backend_rust")]
18 pub struct ZstdDecompressionObj {
19 dctx: Arc<DCtx<'static>>,
20 write_size: usize,
21 read_across_frames: bool,
22 finished: bool,
23 unused_data: Vec<u8>,
24 }
25
26 unsafe impl Sync for ZstdDecompressionObj {}
27
28 impl ZstdDecompressionObj {
29 pub fn new(
30 dctx: Arc<DCtx<'static>>,
31 write_size: usize,
32 read_across_frames: bool,
33 ) -> PyResult<Self> {
34 Ok(ZstdDecompressionObj {
35 dctx,
36 write_size,
37 read_across_frames,
38 finished: false,
39 unused_data: vec![],
40 })
41 }
42 }
43
44 #[pymethods]
45 impl ZstdDecompressionObj {
46 fn decompress<'p>(&mut self, py: Python<'p>, data: PyBuffer<u8>) -> PyResult<Bound<'p, PyAny>> {
47 if self.finished {
48 return Err(ZstdError::new_err(
49 "cannot use a decompressobj multiple times",
50 ));
51 }
52
53 if data.len_bytes() == 0 {
54 return Ok(PyBytes::new(py, &[]).into_any());
55 }
56
57 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
58 src: data.buf_ptr(),
59 size: data.len_bytes(),
60 pos: 0,
61 };
62
63 let mut dest_buffer: Vec<u8> = Vec::with_capacity(self.write_size);
64
65 let chunks = PyList::empty(py);
66
67 loop {
68 let zresult = self
69 .dctx
70 .decompress_into_vec(&mut dest_buffer, &mut in_buffer)
71 .map_err(|msg| ZstdError::new_err(format!("zstd decompress error: {}", msg)))?;
72
73 if !dest_buffer.is_empty() {
74 // TODO avoid buffer copy.
75 let chunk = PyBytes::new(py, &dest_buffer);
76 chunks.append(chunk)?;
77 }
78
79 if zresult == 0 && !self.read_across_frames {
80 self.finished = true;
81 // TODO clear out decompressor?
82
83 if let Some(data) = data.as_slice(py) {
84 let unused = &data[in_buffer.pos..in_buffer.size];
85 self.unused_data = unused.iter().map(|x| x.get()).collect::<Vec<_>>();
86 }
87
88 break;
89 } else if zresult == 0 && self.read_across_frames {
90 if in_buffer.pos == in_buffer.size {
91 break;
92 } else {
93 dest_buffer.clear();
94 }
95 } else if in_buffer.pos == in_buffer.size && dest_buffer.len() < dest_buffer.capacity()
96 {
97 break;
98 } else {
99 dest_buffer.clear();
100 }
101 }
102
103 let empty = PyBytes::new(py, &[]);
104 empty.call_method1("join", (chunks,))
105 }
106
107 #[pyo3(signature = (length=None))]
108 #[allow(unused_variables)]
109 fn flush<'p>(&self, py: Python<'p>, length: Option<usize>) -> PyResult<Bound<'p, PyBytes>> {
110 Ok(PyBytes::new(py, &[]))
111 }
112
113 #[getter]
114 fn unused_data<'p>(&self, py: Python<'p>) -> Bound<'p, PyBytes> {
115 PyBytes::new(py, &self.unused_data)
116 }
117
118 #[getter]
119 fn unconsumed_tail<'p>(&self, py: Python<'p>) -> Bound<'p, PyBytes> {
120 PyBytes::new(py, &[])
121 }
122
123 #[getter]
124 fn eof(&self) -> bool {
125 self.finished
126 }
127 }