| 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::{ |
| 9 |
exceptions::ZstdError, |
| 10 |
stream::{make_in_buffer_source, InBufferSource}, |
| 11 |
zstd_safe::CCtx, |
| 12 |
}, |
| 13 |
pyo3::{ |
| 14 |
buffer::PyBuffer, |
| 15 |
exceptions::{PyOSError, PyValueError}, |
| 16 |
prelude::*, |
| 17 |
types::{PyBytes, PyList}, |
| 18 |
}, |
| 19 |
std::sync::Arc, |
| 20 |
}; |
| 21 |
|
| 22 |
#[pyclass(module = "zstandard.backend_rust")] |
| 23 |
pub struct ZstdCompressionReader { |
| 24 |
cctx: Arc<CCtx<'static>>, |
| 25 |
source: Box<dyn InBufferSource + Send>, |
| 26 |
closefd: bool, |
| 27 |
closed: bool, |
| 28 |
entered: bool, |
| 29 |
bytes_compressed: usize, |
| 30 |
finished_output: bool, |
| 31 |
} |
| 32 |
|
| 33 |
unsafe impl Sync for ZstdCompressionReader {} |
| 34 |
|
| 35 |
impl ZstdCompressionReader { |
| 36 |
pub fn new( |
| 37 |
py: Python, |
| 38 |
cctx: Arc<CCtx<'static>>, |
| 39 |
reader: &Bound<'_, PyAny>, |
| 40 |
size: u64, |
| 41 |
read_size: usize, |
| 42 |
closefd: bool, |
| 43 |
) -> PyResult<Self> { |
| 44 |
let source = make_in_buffer_source(py, reader, read_size)?; |
| 45 |
|
| 46 |
let size = match source.source_size() { |
| 47 |
Some(size) => size as _, |
| 48 |
None => size, |
| 49 |
}; |
| 50 |
|
| 51 |
cctx.set_pledged_source_size(size).or_else(|msg| { |
| 52 |
Err(ZstdError::new_err(format!( |
| 53 |
"error setting source size: {}", |
| 54 |
msg |
| 55 |
))) |
| 56 |
})?; |
| 57 |
|
| 58 |
Ok(Self { |
| 59 |
cctx, |
| 60 |
source, |
| 61 |
closefd, |
| 62 |
closed: false, |
| 63 |
entered: false, |
| 64 |
bytes_compressed: 0, |
| 65 |
finished_output: false, |
| 66 |
}) |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
impl ZstdCompressionReader { |
| 71 |
fn compress_into_buffer( |
| 72 |
&mut self, |
| 73 |
py: Python, |
| 74 |
out_buffer: &mut zstd_sys::ZSTD_outBuffer, |
| 75 |
) -> PyResult<bool> { |
| 76 |
if let Some(mut in_buffer) = self.source.input_buffer(py)? { |
| 77 |
let old_in_pos = in_buffer.pos; |
| 78 |
let old_out_pos = out_buffer.pos; |
| 79 |
|
| 80 |
self.cctx |
| 81 |
.compress_buffers( |
| 82 |
out_buffer, |
| 83 |
&mut in_buffer, |
| 84 |
zstd_sys::ZSTD_EndDirective::ZSTD_e_continue, |
| 85 |
) |
| 86 |
.map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?; |
| 87 |
|
| 88 |
self.bytes_compressed += out_buffer.pos - old_out_pos; |
| 89 |
self.source.record_bytes_read(in_buffer.pos - old_in_pos); |
| 90 |
|
| 91 |
Ok(out_buffer.pos > 0 && out_buffer.pos == out_buffer.size) |
| 92 |
} else { |
| 93 |
Ok(false) |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
fn compress_into_vec(&mut self, py: Python, dest_buffer: &mut Vec<u8>) -> PyResult<bool> { |
| 98 |
let mut out_buffer = zstd_sys::ZSTD_outBuffer { |
| 99 |
dst: dest_buffer.as_mut_ptr() as *mut _, |
| 100 |
size: dest_buffer.capacity(), |
| 101 |
pos: dest_buffer.len(), |
| 102 |
}; |
| 103 |
|
| 104 |
let res = self.compress_into_buffer(py, &mut out_buffer)?; |
| 105 |
|
| 106 |
unsafe { |
| 107 |
dest_buffer.set_len(out_buffer.pos); |
| 108 |
} |
| 109 |
|
| 110 |
Ok(res) |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
#[pymethods] |
| 115 |
impl ZstdCompressionReader { |
| 116 |
// PyIterProtocol. |
| 117 |
|
| 118 |
fn __iter__(slf: PyRef<Self>) -> PyResult<()> { |
| 119 |
let py = slf.py(); |
| 120 |
let io = py.import("io")?; |
| 121 |
let exc = io.getattr("UnsupportedOperation")?; |
| 122 |
|
| 123 |
Err(PyErr::from_value(exc)) |
| 124 |
} |
| 125 |
|
| 126 |
fn __next__(slf: PyRef<Self>) -> PyResult<Option<()>> { |
| 127 |
let py = slf.py(); |
| 128 |
let io = py.import("io")?; |
| 129 |
let exc = io.getattr("UnsupportedOperation")?; |
| 130 |
|
| 131 |
Err(PyErr::from_value(exc)) |
| 132 |
} |
| 133 |
|
| 134 |
fn __enter__<'p>(mut slf: PyRefMut<'p, Self>, _py: Python<'p>) -> PyResult<PyRefMut<'p, Self>> { |
| 135 |
if slf.entered { |
| 136 |
Err(PyValueError::new_err("cannot __enter__ multiple times")) |
| 137 |
} else if slf.closed { |
| 138 |
Err(PyValueError::new_err("stream is closed")) |
| 139 |
} else { |
| 140 |
slf.entered = true; |
| 141 |
Ok(slf) |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
fn __exit__<'p>( |
| 146 |
mut slf: PyRefMut<'p, Self>, |
| 147 |
py: Python<'p>, |
| 148 |
_exc_type: PyObject, |
| 149 |
_exc_value: PyObject, |
| 150 |
_exc_tb: PyObject, |
| 151 |
) -> PyResult<bool> { |
| 152 |
slf.entered = false; |
| 153 |
slf.close(py)?; |
| 154 |
|
| 155 |
// TODO release cctx and reader? |
| 156 |
|
| 157 |
Ok(false) |
| 158 |
} |
| 159 |
|
| 160 |
fn readable(&self) -> bool { |
| 161 |
true |
| 162 |
} |
| 163 |
|
| 164 |
fn writable(&self) -> bool { |
| 165 |
false |
| 166 |
} |
| 167 |
|
| 168 |
fn seekable(&self) -> bool { |
| 169 |
false |
| 170 |
} |
| 171 |
|
| 172 |
fn readline(&self, py: Python) -> PyResult<()> { |
| 173 |
let io = py.import("io")?; |
| 174 |
let exc = io.getattr("UnsupportedOperation")?; |
| 175 |
|
| 176 |
Err(PyErr::from_value(exc)) |
| 177 |
} |
| 178 |
|
| 179 |
#[pyo3(signature = (hint=None))] |
| 180 |
#[allow(unused_variables)] |
| 181 |
fn readlines(&self, py: Python, hint: Option<&Bound<'_, PyAny>>) -> PyResult<()> { |
| 182 |
let io = py.import("io")?; |
| 183 |
let exc = io.getattr("UnsupportedOperation")?; |
| 184 |
|
| 185 |
Err(PyErr::from_value(exc)) |
| 186 |
} |
| 187 |
|
| 188 |
fn write(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> { |
| 189 |
Err(PyOSError::new_err("stream is not writable")) |
| 190 |
} |
| 191 |
|
| 192 |
fn writelines(&self, _data: &Bound<'_, PyAny>) -> PyResult<()> { |
| 193 |
Err(PyOSError::new_err("stream is not writable")) |
| 194 |
} |
| 195 |
|
| 196 |
fn isatty(&self) -> bool { |
| 197 |
false |
| 198 |
} |
| 199 |
|
| 200 |
fn flush(&self) -> PyResult<()> { |
| 201 |
Ok(()) |
| 202 |
} |
| 203 |
|
| 204 |
fn close(&mut self, py: Python) -> PyResult<()> { |
| 205 |
if self.closed { |
| 206 |
return Ok(()); |
| 207 |
} |
| 208 |
|
| 209 |
self.closed = true; |
| 210 |
|
| 211 |
if let Ok(close) = self.source.source_object().getattr(py, "close") { |
| 212 |
if self.closefd { |
| 213 |
close.call0(py)?; |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
Ok(()) |
| 218 |
} |
| 219 |
|
| 220 |
#[getter] |
| 221 |
fn closed(&self) -> bool { |
| 222 |
self.closed |
| 223 |
} |
| 224 |
|
| 225 |
fn tell(&self) -> usize { |
| 226 |
self.bytes_compressed |
| 227 |
} |
| 228 |
|
| 229 |
fn readall<'p>(&mut self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> { |
| 230 |
let chunks = PyList::empty(py); |
| 231 |
|
| 232 |
loop { |
| 233 |
let chunk = self.read(py, 1048576)?; |
| 234 |
|
| 235 |
if chunk.len()? == 0 { |
| 236 |
break; |
| 237 |
} |
| 238 |
|
| 239 |
chunks.append(chunk)?; |
| 240 |
} |
| 241 |
|
| 242 |
let empty = PyBytes::new(py, &[]); |
| 243 |
|
| 244 |
empty.call_method1("join", (chunks,)) |
| 245 |
} |
| 246 |
|
| 247 |
#[pyo3(signature = (size=-1))] |
| 248 |
fn read<'p>(&mut self, py: Python<'p>, size: isize) -> PyResult<Bound<'p, PyAny>> { |
| 249 |
if self.closed { |
| 250 |
return Err(PyValueError::new_err("stream is closed")); |
| 251 |
} |
| 252 |
|
| 253 |
if size < -1 { |
| 254 |
return Err(PyValueError::new_err( |
| 255 |
"cannot read negative amounts less than -1", |
| 256 |
)); |
| 257 |
} |
| 258 |
|
| 259 |
if size == -1 { |
| 260 |
return self.readall(py); |
| 261 |
} |
| 262 |
|
| 263 |
if self.finished_output || size == 0 { |
| 264 |
return Ok(PyBytes::new(py, &[]).into_any()); |
| 265 |
} |
| 266 |
|
| 267 |
let mut dest_buffer: Vec<u8> = Vec::with_capacity(size as _); |
| 268 |
|
| 269 |
while !self.source.finished() { |
| 270 |
// If the output buffer is full, return its content. |
| 271 |
if self.compress_into_vec(py, &mut dest_buffer)? { |
| 272 |
// TODO avoid buffer copy. |
| 273 |
return Ok(PyBytes::new(py, &dest_buffer).into_any()); |
| 274 |
} |
| 275 |
// Else continue to read new input into the compressor. |
| 276 |
} |
| 277 |
|
| 278 |
// EOF. |
| 279 |
let old_pos = dest_buffer.len(); |
| 280 |
|
| 281 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 282 |
src: std::ptr::null_mut(), |
| 283 |
size: 0, |
| 284 |
pos: 0, |
| 285 |
}; |
| 286 |
|
| 287 |
let zresult = self |
| 288 |
.cctx |
| 289 |
.compress_into_vec( |
| 290 |
&mut dest_buffer, |
| 291 |
&mut in_buffer, |
| 292 |
zstd_sys::ZSTD_EndDirective::ZSTD_e_end, |
| 293 |
) |
| 294 |
.map_err(|msg| { |
| 295 |
ZstdError::new_err(format!("error ending compression stream: {}", msg)) |
| 296 |
})?; |
| 297 |
|
| 298 |
self.bytes_compressed += dest_buffer.len() - old_pos; |
| 299 |
|
| 300 |
if zresult == 0 { |
| 301 |
self.finished_output = true; |
| 302 |
} |
| 303 |
|
| 304 |
// TODO avoid buffer copy. |
| 305 |
Ok(PyBytes::new(py, &dest_buffer).into_any()) |
| 306 |
} |
| 307 |
|
| 308 |
#[pyo3(signature = (size=-1))] |
| 309 |
fn read1<'p>(&mut self, py: Python<'p>, size: isize) -> PyResult<Bound<'p, PyAny>> { |
| 310 |
if self.closed { |
| 311 |
return Err(PyValueError::new_err("stream is closed")); |
| 312 |
} |
| 313 |
|
| 314 |
if size < -1 { |
| 315 |
return Err(PyValueError::new_err( |
| 316 |
"cannot read negative amounts less than -1", |
| 317 |
)); |
| 318 |
} |
| 319 |
|
| 320 |
if self.finished_output || size == 0 { |
| 321 |
return Ok(PyBytes::new(py, &[]).into_any()); |
| 322 |
} |
| 323 |
|
| 324 |
// -1 returns arbitrary number of bytes. |
| 325 |
let size = if size == -1 { |
| 326 |
zstd_safe::CCtx::out_size() |
| 327 |
} else { |
| 328 |
size as _ |
| 329 |
}; |
| 330 |
|
| 331 |
let mut dest_buffer: Vec<u8> = Vec::with_capacity(size); |
| 332 |
|
| 333 |
// read1() dictates that we can perform at most 1 call to the |
| 334 |
// underlying stream to get input. However, we can't satisfy this |
| 335 |
// restriction with compression because not all input generates output. |
| 336 |
// It is possible to perform a block flush in order to ensure output. |
| 337 |
// But this may not be desirable behavior. So we allow multiple read() |
| 338 |
// to the underlying stream. But unlike our read(), we stop once we |
| 339 |
// have any output. |
| 340 |
|
| 341 |
// Read data until we exhaust input or have output data. |
| 342 |
while !self.source.finished() && dest_buffer.is_empty() { |
| 343 |
self.compress_into_vec(py, &mut dest_buffer)?; |
| 344 |
} |
| 345 |
|
| 346 |
// We return immediately if: |
| 347 |
// a) output buffer is full |
| 348 |
// b) output buffer has data and input isn't exhausted. |
| 349 |
if dest_buffer.len() == dest_buffer.capacity() |
| 350 |
|| (!dest_buffer.is_empty() && !self.source.finished()) |
| 351 |
{ |
| 352 |
// TODO avoid buffer copy. |
| 353 |
return Ok(PyBytes::new(py, &dest_buffer).into_any()); |
| 354 |
} |
| 355 |
|
| 356 |
// Input must be exhausted. Finish the compression stream. |
| 357 |
let old_pos = dest_buffer.len(); |
| 358 |
|
| 359 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 360 |
src: std::ptr::null_mut(), |
| 361 |
size: 0, |
| 362 |
pos: 0, |
| 363 |
}; |
| 364 |
|
| 365 |
let zresult = self |
| 366 |
.cctx |
| 367 |
.compress_into_vec( |
| 368 |
&mut dest_buffer, |
| 369 |
&mut in_buffer, |
| 370 |
zstd_sys::ZSTD_EndDirective::ZSTD_e_end, |
| 371 |
) |
| 372 |
.map_err(|msg| { |
| 373 |
ZstdError::new_err(format!("error ending compression stream: {}", msg)) |
| 374 |
})?; |
| 375 |
|
| 376 |
self.bytes_compressed += dest_buffer.len() - old_pos; |
| 377 |
|
| 378 |
if zresult == 0 { |
| 379 |
self.finished_output = true; |
| 380 |
} |
| 381 |
|
| 382 |
// TODO avoid buffer copy |
| 383 |
Ok(PyBytes::new(py, &dest_buffer).into_any()) |
| 384 |
} |
| 385 |
|
| 386 |
fn readinto(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> { |
| 387 |
if buffer.readonly() { |
| 388 |
return Err(PyValueError::new_err("buffer is not writable")); |
| 389 |
} |
| 390 |
|
| 391 |
if self.closed { |
| 392 |
return Err(PyValueError::new_err("stream is closed")); |
| 393 |
} |
| 394 |
|
| 395 |
if self.finished_output { |
| 396 |
return Ok(0); |
| 397 |
} |
| 398 |
|
| 399 |
let mut out_buffer = zstd_sys::ZSTD_outBuffer { |
| 400 |
dst: buffer.buf_ptr(), |
| 401 |
size: buffer.len_bytes(), |
| 402 |
pos: 0, |
| 403 |
}; |
| 404 |
|
| 405 |
while !self.source.finished() { |
| 406 |
if self.compress_into_buffer(py, &mut out_buffer)? { |
| 407 |
return Ok(out_buffer.pos); |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
// EOF. |
| 412 |
let old_pos = out_buffer.pos; |
| 413 |
|
| 414 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 415 |
src: std::ptr::null_mut(), |
| 416 |
size: 0, |
| 417 |
pos: 0, |
| 418 |
}; |
| 419 |
|
| 420 |
let zresult = self |
| 421 |
.cctx |
| 422 |
.compress_buffers( |
| 423 |
&mut out_buffer, |
| 424 |
&mut in_buffer, |
| 425 |
zstd_sys::ZSTD_EndDirective::ZSTD_e_end, |
| 426 |
) |
| 427 |
.map_err(|msg| { |
| 428 |
ZstdError::new_err(format!("error ending compression stream: {}", msg)) |
| 429 |
})?; |
| 430 |
|
| 431 |
self.bytes_compressed += out_buffer.pos - old_pos; |
| 432 |
|
| 433 |
if zresult == 0 { |
| 434 |
self.finished_output = true; |
| 435 |
} |
| 436 |
|
| 437 |
Ok(out_buffer.pos) |
| 438 |
} |
| 439 |
|
| 440 |
fn readinto1(&mut self, py: Python, buffer: PyBuffer<u8>) -> PyResult<usize> { |
| 441 |
if buffer.readonly() { |
| 442 |
return Err(PyValueError::new_err("buffer is not writable")); |
| 443 |
} |
| 444 |
|
| 445 |
if self.closed { |
| 446 |
return Err(PyValueError::new_err("stream is closed")); |
| 447 |
} |
| 448 |
|
| 449 |
if self.finished_output { |
| 450 |
return Ok(0); |
| 451 |
} |
| 452 |
|
| 453 |
let mut out_buffer = zstd_sys::ZSTD_outBuffer { |
| 454 |
dst: buffer.buf_ptr(), |
| 455 |
size: buffer.len_bytes(), |
| 456 |
pos: 0, |
| 457 |
}; |
| 458 |
|
| 459 |
// Read until we get output. |
| 460 |
while out_buffer.pos == 0 && !self.source.finished() { |
| 461 |
self.compress_into_buffer(py, &mut out_buffer)?; |
| 462 |
} |
| 463 |
|
| 464 |
// If we still have input, return immediately. |
| 465 |
if !self.source.finished() { |
| 466 |
return Ok(out_buffer.pos); |
| 467 |
} |
| 468 |
|
| 469 |
// EOF. |
| 470 |
let old_pos = out_buffer.pos; |
| 471 |
|
| 472 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 473 |
src: std::ptr::null_mut(), |
| 474 |
size: 0, |
| 475 |
pos: 0, |
| 476 |
}; |
| 477 |
|
| 478 |
let zresult = self |
| 479 |
.cctx |
| 480 |
.compress_buffers( |
| 481 |
&mut out_buffer, |
| 482 |
&mut in_buffer, |
| 483 |
zstd_sys::ZSTD_EndDirective::ZSTD_e_end, |
| 484 |
) |
| 485 |
.map_err(|msg| { |
| 486 |
ZstdError::new_err(format!("error ending compression stream: {}", msg)) |
| 487 |
})?; |
| 488 |
|
| 489 |
self.bytes_compressed += out_buffer.pos - old_pos; |
| 490 |
|
| 491 |
if zresult == 0 { |
| 492 |
self.finished_output = true; |
| 493 |
} |
| 494 |
|
| 495 |
Ok(out_buffer.pos) |
| 496 |
} |
| 497 |
} |