forked from indygreg/python-zstandard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompression_chunker.rs
More file actions
283 lines (233 loc) · 8.38 KB
/
Copy pathcompression_chunker.rs
File metadata and controls
283 lines (233 loc) · 8.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Copyright (c) 2020-present, Gregory Szorc
// All rights reserved.
//
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
use {
crate::{
exceptions::ZstdError,
stream::{make_in_buffer_source, InBufferSource},
zstd_safe::CCtx,
},
pyo3::{prelude::*, types::PyBytes, IntoPyObjectExt},
std::sync::Arc,
};
#[pyclass(module = "zstandard.backend_rust")]
pub struct ZstdCompressionChunker {
cctx: Arc<CCtx<'static>>,
chunk_size: usize,
finished: bool,
iterator: Option<Py<ZstdCompressionChunkerIterator>>,
partial_buffer: Option<Vec<u8>>,
}
unsafe impl Sync for ZstdCompressionChunker {}
impl ZstdCompressionChunker {
pub fn new(cctx: Arc<CCtx<'static>>, chunk_size: usize) -> PyResult<Self> {
Ok(Self {
cctx,
chunk_size,
finished: false,
iterator: None,
partial_buffer: None,
})
}
}
impl ZstdCompressionChunker {
fn ensure_state(&mut self, py: Python) {
if let Some(it) = &self.iterator {
if it.borrow(py).finished {
if it.borrow(py).mode == IteratorMode::Finish {
self.finished = true;
}
if !it.borrow(py).dest_buffer.is_empty() {
// TODO can we avoid the memory copy?
// Vec.clone() won't preserve the capacity of the source.
// So we create a new Vec with desired capacity and copy to it.
// This is strictly better than a clone + resize.
let mut dest_buffer = Vec::with_capacity(self.chunk_size);
unsafe {
dest_buffer.set_len(it.borrow(py).dest_buffer.len());
}
dest_buffer.copy_from_slice(it.borrow(py).dest_buffer.as_slice());
self.partial_buffer = Some(dest_buffer);
}
self.iterator = None;
}
}
}
fn get_dest_buffer(&mut self) -> Vec<u8> {
self.partial_buffer
.take()
.unwrap_or_else(|| Vec::with_capacity(self.chunk_size))
}
}
#[pymethods]
impl ZstdCompressionChunker {
fn compress(
&mut self,
py: Python,
data: &Bound<'_, PyAny>,
) -> PyResult<Py<ZstdCompressionChunkerIterator>> {
self.ensure_state(py);
if self.finished {
return Err(ZstdError::new_err(
"cannot call compress() after compression finished",
));
}
let source = make_in_buffer_source(py, data, zstd_safe::CCtx::in_size())?;
let it = Bound::new(
py,
ZstdCompressionChunkerIterator {
cctx: self.cctx.clone(),
source,
mode: IteratorMode::Normal,
dest_buffer: self.get_dest_buffer(),
finished: false,
},
)?;
self.iterator = Some(it.clone().unbind());
Ok(it.unbind())
}
fn flush<'p>(&mut self, py: Python<'p>) -> PyResult<Py<ZstdCompressionChunkerIterator>> {
self.ensure_state(py);
if self.finished {
return Err(ZstdError::new_err(
"cannot call flush() after compression finished",
));
}
if self.iterator.is_some() {
return Err(ZstdError::new_err(
"cannot call flush() before consuming output from previous operation",
));
}
let source =
make_in_buffer_source(py, &PyBytes::new(py, &[]), zstd_safe::CCtx::in_size())?;
let it = Bound::new(
py,
ZstdCompressionChunkerIterator {
cctx: self.cctx.clone(),
source,
mode: IteratorMode::Flush,
dest_buffer: self.get_dest_buffer(),
finished: false,
},
)?;
self.iterator = Some(it.clone().unbind());
Ok(it.unbind())
}
fn finish<'p>(&mut self, py: Python<'p>) -> PyResult<Py<ZstdCompressionChunkerIterator>> {
self.ensure_state(py);
if self.finished {
return Err(ZstdError::new_err(
"cannot call finish() after compression finished",
));
}
if self.iterator.is_some() {
return Err(ZstdError::new_err(
"cannot call finish() before consuming output from previous operation",
));
}
let source =
make_in_buffer_source(py, &PyBytes::new(py, &[]), zstd_safe::CCtx::in_size())?;
let it = Bound::new(
py,
ZstdCompressionChunkerIterator {
cctx: self.cctx.clone(),
source,
mode: IteratorMode::Finish,
dest_buffer: self.get_dest_buffer(),
finished: false,
},
)?;
self.iterator = Some(it.clone().unbind());
Ok(it.unbind())
}
}
#[derive(Debug, PartialEq)]
enum IteratorMode {
Normal,
Flush,
Finish,
}
#[pyclass(module = "zstandard.backend_rust")]
struct ZstdCompressionChunkerIterator {
cctx: Arc<CCtx<'static>>,
source: Box<dyn InBufferSource + Send>,
mode: IteratorMode,
dest_buffer: Vec<u8>,
finished: bool,
}
unsafe impl Sync for ZstdCompressionChunkerIterator {}
#[pymethods]
impl ZstdCompressionChunkerIterator {
// PyIterProtocol.
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<PyObject>> {
if slf.finished {
return Ok(None);
}
let py = unsafe { Python::assume_gil_acquired() };
// Consume any data left in the input.
while let Some(mut in_buffer) = slf.source.input_buffer(py)? {
let old_pos = in_buffer.pos;
slf.cctx
.clone()
.compress_into_vec(
&mut slf.dest_buffer,
&mut in_buffer,
zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
)
.map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
slf.source.record_bytes_read(in_buffer.pos - old_pos);
// If we produced a full output chunk, emit it.
if slf.dest_buffer.len() == slf.dest_buffer.capacity() {
let chunk = PyBytes::new(py, &slf.dest_buffer);
slf.dest_buffer.clear();
return Ok(Some(chunk.into_py_any(py).unwrap()));
}
// Else continue to compress available input data.
continue;
}
// No more input data. A partial chunk may be in the destination
// buffer. If we're in normal compression mode, we're done. Otherwise
// if we're in flush or finish mode, we need to emit what data remains.
let flush_mode = match slf.mode {
IteratorMode::Normal => {
slf.finished = true;
return Ok(None);
}
IteratorMode::Flush => zstd_sys::ZSTD_EndDirective::ZSTD_e_flush,
IteratorMode::Finish => zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
};
let mut in_buffer = zstd_sys::ZSTD_inBuffer {
src: std::ptr::null(),
size: 0,
pos: 0,
};
let zresult = slf
.cctx
.clone()
.compress_into_vec(&mut slf.dest_buffer, &mut in_buffer, flush_mode)
.map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
// When flushing or finishing, we always emit data in the output
// buffer. But the operation could fill the output buffer and not be
// finished.
// If we didn't emit anything to the output buffer, we must be finished.
// Update state and stop iteration.
if slf.dest_buffer.is_empty() {
slf.finished = true;
return Ok(None);
}
// If the flush or finish didn't fill the output buffer, we must
// be done.
// If compressor said operation is finished, we are also done.
if zresult == 0 || slf.dest_buffer.len() < slf.dest_buffer.capacity() {
slf.finished = true;
}
let chunk = PyBytes::new(py, &slf.dest_buffer);
slf.dest_buffer.clear();
Ok(Some(chunk.into_py_any(py).unwrap()))
}
}