-
-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathcompression_reader.rs
More file actions
501 lines (404 loc) · 13.4 KB
/
compression_reader.rs
File metadata and controls
501 lines (404 loc) · 13.4 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// 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::{
buffer::PyBuffer,
exceptions::{PyOSError, PyValueError},
prelude::*,
types::{PyBytes, PyList},
},
std::sync::Arc,
};
#[pyclass(module = "zstandard.backend_rust")]
pub struct ZstdCompressionReader {
cctx: Arc<CCtx<'static>>,
source: Box<dyn InBufferSource + Send>,
closefd: bool,
closed: bool,
entered: bool,
bytes_compressed: usize,
finished_output: bool,
}
unsafe impl Sync for ZstdCompressionReader {}
impl ZstdCompressionReader {
pub fn new(
py: Python,
cctx: Arc<CCtx<'static>>,
reader: &Bound<'_, PyAny>,
size: u64,
read_size: usize,
closefd: bool,
) -> PyResult<Self> {
let source = make_in_buffer_source(py, reader, read_size)?;
let size = match source.source_size() {
Some(size) => size as _,
None => size,
};
cctx.set_pledged_source_size(size).or_else(|msg| {
Err(ZstdError::new_err(format!(
"error setting source size: {}",
msg
)))
})?;
Ok(Self {
cctx,
source,
closefd,
closed: false,
entered: false,
bytes_compressed: 0,
finished_output: false,
})
}
}
impl ZstdCompressionReader {
fn compress_into_buffer(
&mut self,
py: Python,
out_buffer: &mut zstd_sys::ZSTD_outBuffer,
) -> PyResult<bool> {
if let Some(mut in_buffer) = self.source.input_buffer(py)? {
let old_in_pos = in_buffer.pos;
let old_out_pos = out_buffer.pos;
self.cctx
.compress_buffers(
out_buffer,
&mut in_buffer,
zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
)
.map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?;
self.bytes_compressed += out_buffer.pos - old_out_pos;
self.source.record_bytes_read(in_buffer.pos - old_in_pos);
Ok(out_buffer.pos > 0 && out_buffer.pos == out_buffer.size)
} else {
Ok(false)
}
}
fn compress_into_vec(&mut self, py: Python, dest_buffer: &mut Vec<u8>) -> PyResult<bool> {
let mut out_buffer = zstd_sys::ZSTD_outBuffer {
dst: dest_buffer.as_mut_ptr() as *mut _,
size: dest_buffer.capacity(),
pos: dest_buffer.len(),
};
let res = self.compress_into_buffer(py, &mut out_buffer)?;
unsafe {
dest_buffer.set_len(out_buffer.pos);
}
Ok(res)
}
}
#[pymethods]
impl ZstdCompressionReader {
// PyIterProtocol.
fn __iter__(slf: PyRef<Self>) -> PyResult<()> {
let py = slf.py();
let io = py.import("io")?;
let exc = io.getattr("UnsupportedOperation")?;
Err(PyErr::from_value(exc))
}
fn __next__(slf: PyRef<Self>) -> PyResult<Option<()>> {
let py = slf.py();
let io = py.import("io")?;
let exc = io.getattr("UnsupportedOperation")?;
Err(PyErr::from_value(exc))
}
fn __enter__<'p>(mut slf: PyRefMut<'p, Self>, _py: Python<'p>) -> PyResult<PyRefMut<'p, Self>> {
if slf.entered {
Err(PyValueError::new_err("cannot __enter__ multiple times"))
} else if slf.closed {
Err(PyValueError::new_err("stream is closed"))
} else {
slf.entered = true;
Ok(slf)
}
}
fn __exit__<'p>(
mut slf: PyRefMut<'p, Self>,
py: Python<'p>,
_exc_type: PyObject,
_exc_value: PyObject,
_exc_tb: PyObject,
) -> PyResult<bool> {
slf.entered = false;
slf.close(py)?;
// TODO release cctx and reader?
Ok(false)
}
fn readable(&self) -> bool {
true
}
fn writable(&self) -> bool {
false
}
fn seekable(&self) -> bool {
false
}
fn seek(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> {
Err(PyOSError::new_err("stream is not seekable"))
}
fn readline(&self, py: Python) -> PyResult<()> {
let io = py.import("io")?;
let exc = io.getattr("UnsupportedOperation")?;
Err(PyErr::from_value(exc))
}
#[pyo3(signature = (hint=None))]
#[allow(unused_variables)]
fn readlines(&self, py: Python, hint: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
let io = py.import("io")?;
let exc = io.getattr("UnsupportedOperation")?;
Err(PyErr::from_value(exc))
}
fn write(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> {
Err(PyOSError::new_err("stream is not writable"))
}
fn writelines(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> {
Err(PyOSError::new_err("stream is not writable"))
}
fn isatty(&self) -> bool {
false
}
fn flush(&self) -> PyResult<()> {
Ok(())
}
fn close(&mut self, py: Python) -> PyResult<()> {
if self.closed {
return Ok(());
}
self.closed = true;
if let Ok(close) = self.source.source_object().getattr(py, "close") {
if self.closefd {
close.call0(py)?;
}
}
Ok(())
}
#[getter]
fn closed(&self) -> bool {
self.closed
}
fn tell(&self) -> usize {
self.bytes_compressed
}
fn readall<'p>(&mut self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
let chunks = PyList::empty(py);
loop {
let chunk = self.read(py, 1048576)?;
if chunk.len()? == 0 {
break;
}
chunks.append(chunk)?;
}
let empty = PyBytes::new(py, &[]);
empty.call_method1("join", (chunks,))
}
#[pyo3(signature = (size=-1))]
fn read<'p>(&mut self, py: Python<'p>, size: isize) -> PyResult<Bound<'p, PyAny>> {
if self.closed {
return Err(PyValueError::new_err("stream is closed"));
}
if size < -1 {
return Err(PyValueError::new_err(
"cannot read negative amounts less than -1",
));
}
if size == -1 {
return self.readall(py);
}
if self.finished_output || size == 0 {
return Ok(PyBytes::new(py, &[]).into_any());
}
let mut dest_buffer: Vec<u8> = Vec::with_capacity(size as _);
while !self.source.finished() {
// If the output buffer is full, return its content.
if self.compress_into_vec(py, &mut dest_buffer)? {
// TODO avoid buffer copy.
return Ok(PyBytes::new(py, &dest_buffer).into_any());
}
// Else continue to read new input into the compressor.
}
// EOF.
let old_pos = dest_buffer.len();
let mut in_buffer = zstd_sys::ZSTD_inBuffer {
src: std::ptr::null_mut(),
size: 0,
pos: 0,
};
let zresult = self
.cctx
.compress_into_vec(
&mut dest_buffer,
&mut in_buffer,
zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
)
.map_err(|msg| {
ZstdError::new_err(format!("error ending compression stream: {}", msg))
})?;
self.bytes_compressed += dest_buffer.len() - old_pos;
if zresult == 0 {
self.finished_output = true;
}
// TODO avoid buffer copy.
Ok(PyBytes::new(py, &dest_buffer).into_any())
}
#[pyo3(signature = (size=-1))]
fn read1<'p>(&mut self, py: Python<'p>, size: isize) -> PyResult<Bound<'p, PyAny>> {
if self.closed {
return Err(PyValueError::new_err("stream is closed"));
}
if size < -1 {
return Err(PyValueError::new_err(
"cannot read negative amounts less than -1",
));
}
if self.finished_output || size == 0 {
return Ok(PyBytes::new(py, &[]).into_any());
}
// -1 returns arbitrary number of bytes.
let size = if size == -1 {
zstd_safe::CCtx::out_size()
} else {
size as _
};
let mut dest_buffer: Vec<u8> = Vec::with_capacity(size);
// read1() dictates that we can perform at most 1 call to the
// underlying stream to get input. However, we can't satisfy this
// restriction with compression because not all input generates output.
// It is possible to perform a block flush in order to ensure output.
// But this may not be desirable behavior. So we allow multiple read()
// to the underlying stream. But unlike our read(), we stop once we
// have any output.
// Read data until we exhaust input or have output data.
while !self.source.finished() && dest_buffer.is_empty() {
self.compress_into_vec(py, &mut dest_buffer)?;
}
// We return immediately if:
// a) output buffer is full
// b) output buffer has data and input isn't exhausted.
if dest_buffer.len() == dest_buffer.capacity()
|| (!dest_buffer.is_empty() && !self.source.finished())
{
// TODO avoid buffer copy.
return Ok(PyBytes::new(py, &dest_buffer).into_any());
}
// Input must be exhausted. Finish the compression stream.
let old_pos = dest_buffer.len();
let mut in_buffer = zstd_sys::ZSTD_inBuffer {
src: std::ptr::null_mut(),
size: 0,
pos: 0,
};
let zresult = self
.cctx
.compress_into_vec(
&mut dest_buffer,
&mut in_buffer,
zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
)
.map_err(|msg| {
ZstdError::new_err(format!("error ending compression stream: {}", msg))
})?;
self.bytes_compressed += dest_buffer.len() - old_pos;
if zresult == 0 {
self.finished_output = true;
}
// TODO avoid buffer copy
Ok(PyBytes::new(py, &dest_buffer).into_any())
}
fn readinto(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> {
if buffer.readonly() {
return Err(PyValueError::new_err("buffer is not writable"));
}
if self.closed {
return Err(PyValueError::new_err("stream is closed"));
}
if self.finished_output {
return Ok(0);
}
let mut out_buffer = zstd_sys::ZSTD_outBuffer {
dst: buffer.buf_ptr(),
size: buffer.len_bytes(),
pos: 0,
};
while !self.source.finished() {
if self.compress_into_buffer(py, &mut out_buffer)? {
return Ok(out_buffer.pos);
}
}
// EOF.
let old_pos = out_buffer.pos;
let mut in_buffer = zstd_sys::ZSTD_inBuffer {
src: std::ptr::null_mut(),
size: 0,
pos: 0,
};
let zresult = self
.cctx
.compress_buffers(
&mut out_buffer,
&mut in_buffer,
zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
)
.map_err(|msg| {
ZstdError::new_err(format!("error ending compression stream: {}", msg))
})?;
self.bytes_compressed += out_buffer.pos - old_pos;
if zresult == 0 {
self.finished_output = true;
}
Ok(out_buffer.pos)
}
fn readinto1(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> {
if buffer.readonly() {
return Err(PyValueError::new_err("buffer is not writable"));
}
if self.closed {
return Err(PyValueError::new_err("stream is closed"));
}
if self.finished_output {
return Ok(0);
}
let mut out_buffer = zstd_sys::ZSTD_outBuffer {
dst: buffer.buf_ptr(),
size: buffer.len_bytes(),
pos: 0,
};
// Read until we get output.
while out_buffer.pos == 0 && !self.source.finished() {
self.compress_into_buffer(py, &mut out_buffer)?;
}
// If we still have input, return immediately.
if !self.source.finished() {
return Ok(out_buffer.pos);
}
// EOF.
let old_pos = out_buffer.pos;
let mut in_buffer = zstd_sys::ZSTD_inBuffer {
src: std::ptr::null_mut(),
size: 0,
pos: 0,
};
let zresult = self
.cctx
.compress_buffers(
&mut out_buffer,
&mut in_buffer,
zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
)
.map_err(|msg| {
ZstdError::new_err(format!("error ending compression stream: {}", msg))
})?;
self.bytes_compressed += out_buffer.pos - old_pos;
if zresult == 0 {
self.finished_output = true;
}
Ok(out_buffer.pos)
}
}