Debian Codegraph @

contrib/python-zstandard/rust-ext/src/compressor_iterator.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::CCtx,
12 },
13 pyo3::{prelude::*, types::PyBytes},
14 std::sync::Arc,
15 };
16
17 #[pyclass(module = "zstandard.backend_rust")]
18 pub struct ZstdCompressorIterator {
19 cctx: Arc<CCtx<'static>>,
20 source: Box<dyn InBufferSource + Send>,
21 write_size: usize,
22 finished_output: bool,
23 }
24
25 #[pymethods]
26 impl ZstdCompressorIterator {
27 // PyIterProtocol.
28
29 fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
30 slf
31 }
32
33 fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<PyObject>> {
34 if slf.finished_output {
35 return Ok(None);
36 }
37
38 let py = unsafe { Python::assume_gil_acquired() };
39
40 let mut dest_buffer: Vec<u8> = Vec::with_capacity(slf.write_size);
41
42 // Feed data into the compressor until there is output data.
43 while let Some(mut in_buffer) = slf.source.input_buffer(py)? {
44 let old_pos = in_buffer.pos;
45
46 slf.cctx
47 .compress_into_vec(
48 &mut dest_buffer,
49 &mut in_buffer,
50 zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
51 )
52 .map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
53
54 slf.source.record_bytes_read(in_buffer.pos - old_pos);
55
56 // Emit compressed data, if available.
57 if !dest_buffer.is_empty() {
58 // TODO avoid buffer copy
59 let chunk = PyBytes::new_bound(py, &dest_buffer);
60
61 return Ok(Some(chunk.into_py(py)));
62 }
63
64 // Else read another chunk in hopes of producing output data.
65 continue;
66 }
67
68 // Input data is exhausted. End the stream and emit what remains.
69
70 let mut in_buffer = zstd_sys::ZSTD_inBuffer {
71 src: std::ptr::null_mut(),
72 size: 0,
73 pos: 0,
74 };
75
76 let zresult = slf
77 .cctx
78 .compress_into_vec(
79 &mut dest_buffer,
80 &mut in_buffer,
81 zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
82 )
83 .map_err(|msg| {
84 ZstdError::new_err(format!("error ending compression stream: {}", msg))
85 })?;
86
87 if zresult == 0 {
88 slf.finished_output = true;
89 }
90
91 if !dest_buffer.is_empty() {
92 // TODO avoid buffer copy.
93 let chunk = PyBytes::new_bound(py, &dest_buffer);
94
95 return Ok(Some(chunk.into_py(py)));
96 }
97
98 Ok(None)
99 }
100 }
101
102 impl ZstdCompressorIterator {
103 pub fn new(
104 py: Python,
105 cctx: Arc<CCtx<'static>>,
106 reader: &Bound<'_, PyAny>,
107 size: u64,
108 read_size: usize,
109 write_size: usize,
110 ) -> PyResult<Self> {
111 let source = make_in_buffer_source(py, reader, read_size)?;
112
113 let size = match source.source_size() {
114 Some(size) => size as _,
115 None => size,
116 };
117
118 cctx.set_pledged_source_size(size)
119 .map_err(|msg| ZstdError::new_err(format!("error setting source size: {}", msg)))?;
120
121 Ok(Self {
122 cctx,
123 source,
124 write_size,
125 finished_output: false,
126 })
127 }
128 }