Debian Codegraph @

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