Debian Codegraph @

rust-ext/src/compression_writer.rs

raw
1 // Copyright (c) 2020-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::CCtx},
9 pyo3::{
10 buffer::PyBuffer,
11 exceptions::{PyNotImplementedError, PyOSError, PyValueError},
12 prelude::*,
13 types::PyBytes,
14 IntoPyObjectExt,
15 },
16 std::sync::Arc,
17 };
18
19 const FLUSH_BLOCK: usize = 0;
20 const FLUSH_FRAME: usize = 1;
21
22 #[pyclass(module = "zstandard.backend_rust")]
23 pub struct ZstdCompressionWriter {
24 cctx: Arc<CCtx<'static>>,
25 writer: PyObject,
26 write_return_read: bool,
27 closefd: bool,
28 entered: bool,
29 closing: bool,
30 closed: bool,
31 bytes_compressed: usize,
32 dest_buffer: Vec<u8>,
33 }
34
35 unsafe impl Sync for ZstdCompressionWriter {}
36
37 impl ZstdCompressionWriter {
38 pub fn new(
39 py: Python,
40 cctx: Arc<CCtx<'static>>,
41 writer: &Bound<'_, PyAny>,
42 source_size: u64,
43 write_size: usize,
44 write_return_read: bool,
45 closefd: bool,
46 ) -> PyResult<Self> {
47 cctx.set_pledged_source_size(source_size)
48 .map_err(|msg| ZstdError::new_err(format!("error setting source size: {}", msg)))?;
49
50 Ok(Self {
51 cctx,
52 writer: writer.into_py_any(py)?,
53 write_return_read,
54 closefd,
55 entered: false,
56 closing: false,
57 closed: false,
58 bytes_compressed: 0,
59 dest_buffer: Vec::with_capacity(write_size),
60 })
61 }
62 }
63
64 #[pymethods]
65 impl ZstdCompressionWriter {
66 // PyIterProtocol.
67
68 fn __iter__(slf: PyRef<Self>) -> PyResult<()> {
69 let py = slf.py();
70 let io = py.import("io")?;
71 let exc = io.getattr("UnsupportedOperation")?;
72
73 Err(PyErr::from_value(exc))
74 }
75
76 fn __next__(slf: PyRef<Self>) -> PyResult<Option<()>> {
77 let py = slf.py();
78 let io = py.import("io")?;
79 let exc = io.getattr("UnsupportedOperation")?;
80
81 Err(PyErr::from_value(exc))
82 }
83
84 fn __enter__<'p>(mut slf: PyRefMut<'p, Self>, _py: Python<'p>) -> PyResult<PyRefMut<'p, Self>> {
85 if slf.closed {
86 Err(PyValueError::new_err("stream is closed"))
87 } else if slf.entered {
88 Err(ZstdError::new_err("cannot __enter__ multiple times"))
89 } else {
90 slf.entered = true;
91 Ok(slf)
92 }
93 }
94
95 fn __exit__<'p>(
96 mut slf: PyRefMut<'p, Self>,
97 py: Python<'p>,
98 _exc_type: &Bound<'_, PyAny>,
99 _exc_value: &Bound<'_, PyAny>,
100 _exc_tb: &Bound<'_, PyAny>,
101 ) -> PyResult<bool> {
102 slf.entered = false;
103 slf.close(py)?;
104
105 // TODO clear out compressor context?
106
107 Ok(false)
108 }
109
110 fn memory_size(&self) -> usize {
111 self.cctx.memory_size()
112 }
113
114 fn fileno(&self, py: Python) -> PyResult<PyObject> {
115 if let Ok(fileno) = self.writer.getattr(py, "fileno") {
116 fileno.call0(py)
117 } else {
118 Err(PyOSError::new_err(
119 "filenot not available on underlying writer",
120 ))
121 }
122 }
123
124 fn close(&mut self, py: Python) -> PyResult<()> {
125 if self.closed {
126 return Ok(());
127 }
128
129 self.closing = true;
130 let res = self.flush(py, FLUSH_FRAME);
131 self.closing = false;
132 self.closed = true;
133
134 res?;
135
136 // Call close() on underlying stream as well.
137 if let Ok(close) = self.writer.getattr(py, "close") {
138 if self.closefd {
139 close.call0(py)?;
140 }
141 }
142
143 Ok(())
144 }
145
146 #[getter]
147 fn closed(&self) -> bool {
148 self.closed
149 }
150
151 fn isatty(&self) -> bool {
152 false
153 }
154
155 fn readable(&self) -> bool {
156 false
157 }
158
159 #[pyo3(signature = (size=None))]
160 #[allow(unused_variables)]
161 fn readline(&self, py: Python, size: 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 = (hint=None))]
169 #[allow(unused_variables)]
170 fn readlines(&self, py: Python, hint: Option<&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 = (pos, whence=None))]
178 #[allow(unused_variables)]
179 fn seek(&self, py: Python, pos: isize, whence: Option<&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 seekable(&self) -> bool {
187 false
188 }
189
190 #[pyo3(signature = (size=None))]
191 #[allow(unused_variables)]
192 fn truncate(&self, py: Python, size: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
193 let io = py.import("io")?;
194 let exc = io.getattr("UnsupportedOperation")?;
195
196 Err(PyErr::from_value(exc))
197 }
198
199 fn writable(&self) -> bool {
200 true
201 }
202
203 #[allow(unused_variables)]
204 fn writelines(&self, lines: &Bound<'_, PyAny>) -> PyResult<()> {
205 Err(PyNotImplementedError::new_err(()))
206 }
207
208 #[pyo3(signature = (size=None))]
209 #[allow(unused_variables)]
210 fn read(&self, py: Python, size: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
211 let io = py.import("io")?;
212 let exc = io.getattr("UnsupportedOperation")?;
213
214 Err(PyErr::from_value(exc))
215 }
216
217 fn readall(&self, py: Python) -> PyResult<()> {
218 let io = py.import("io")?;
219 let exc = io.getattr("UnsupportedOperation")?;
220
221 Err(PyErr::from_value(exc))
222 }
223
224 #[allow(unused_variables)]
225 fn readinto(&self, py: Python, b: &Bound<'_, PyAny>) -> PyResult<()> {
226 let io = py.import("io")?;
227 let exc = io.getattr("UnsupportedOperation")?;
228
229 Err(PyErr::from_value(exc))
230 }
231
232 fn write(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> {
233 if self.closed {
234 return Err(PyValueError::new_err("stream is closed"));
235 }
236
237 let mut total_write = 0;
238
239 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
240 src: buffer.buf_ptr(),
241 size: buffer.len_bytes(),
242 pos: 0,
243 };
244
245 while in_buffer.pos < in_buffer.size {
246 self.cctx
247 .compress_into_vec(
248 &mut self.dest_buffer,
249 &mut in_buffer,
250 zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
251 )
252 .map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
253
254 if !self.dest_buffer.is_empty() {
255 // TODO avoid buffer copy.
256 let chunk = PyBytes::new(py, &self.dest_buffer);
257 self.writer.call_method1(py, "write", (chunk,))?;
258
259 total_write += self.dest_buffer.len();
260 self.bytes_compressed += self.dest_buffer.len();
261 self.dest_buffer.clear();
262 }
263 }
264
265 if self.write_return_read {
266 Ok(in_buffer.pos)
267 } else {
268 Ok(total_write)
269 }
270 }
271
272 #[pyo3(signature = (flush_mode=FLUSH_BLOCK))]
273 fn flush(&mut self, py: Python, flush_mode: usize) -> PyResult<usize> {
274 let flush = match flush_mode {
275 FLUSH_BLOCK => Ok(zstd_sys::ZSTD_EndDirective::ZSTD_e_flush),
276 FLUSH_FRAME => Ok(zstd_sys::ZSTD_EndDirective::ZSTD_e_end),
277 _ => Err(PyValueError::new_err(format!(
278 "unknown flush_mode: {}",
279 flush_mode
280 ))),
281 }?;
282
283 if self.closed {
284 return Err(PyValueError::new_err("stream is closed"));
285 }
286
287 let mut total_write = 0;
288
289 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
290 src: std::ptr::null_mut(),
291 size: 0,
292 pos: 0,
293 };
294
295 loop {
296 let zresult = self
297 .cctx
298 .compress_into_vec(&mut self.dest_buffer, &mut in_buffer, flush)
299 .map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
300
301 if !self.dest_buffer.is_empty() {
302 // TODO avoid buffer copy.
303 let chunk = PyBytes::new(py, &self.dest_buffer);
304 self.writer.call_method1(py, "write", (chunk,))?;
305
306 total_write += self.dest_buffer.len();
307 self.bytes_compressed += self.dest_buffer.len();
308 self.dest_buffer.clear();
309 }
310
311 if zresult == 0 {
312 break;
313 }
314 }
315
316 if let Ok(flush) = self.writer.getattr(py, "flush") {
317 if !self.closing {
318 flush.call0(py)?;
319 }
320 }
321
322 Ok(total_write)
323 }
324
325 fn tell(&self) -> usize {
326 self.bytes_compressed
327 }
328 }