| 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 |
buffers::ZstdBufferWithSegmentsCollection, compression_dict::ZstdCompressionDict, |
| 10 |
decompression_reader::ZstdDecompressionReader, |
| 11 |
decompression_writer::ZstdDecompressionWriter, decompressionobj::ZstdDecompressionObj, |
| 12 |
decompressor_iterator::ZstdDecompressorIterator, |
| 13 |
decompressor_multi::multi_decompress_to_buffer, exceptions::ZstdError, zstd_safe::DCtx, |
| 14 |
}, |
| 15 |
pyo3::{ |
| 16 |
buffer::PyBuffer, |
| 17 |
exceptions::{PyMemoryError, PyValueError}, |
| 18 |
prelude::*, |
| 19 |
types::{PyBytes, PyList}, |
| 20 |
wrap_pyfunction, |
| 21 |
}, |
| 22 |
std::sync::Arc, |
| 23 |
}; |
| 24 |
|
| 25 |
#[pyclass(module = "zstandard.backend_rust")] |
| 26 |
struct ZstdDecompressor { |
| 27 |
dict_data: Option<Py<ZstdCompressionDict>>, |
| 28 |
max_window_size: usize, |
| 29 |
format: zstd_sys::ZSTD_format_e, |
| 30 |
dctx: Arc<DCtx<'static>>, |
| 31 |
} |
| 32 |
|
| 33 |
impl ZstdDecompressor { |
| 34 |
fn setup_dctx(&self, py: Python, load_dict: bool) -> PyResult<()> { |
| 35 |
self.dctx.reset().map_err(|msg| { |
| 36 |
ZstdError::new_err(format!("unable to reset decompression context: {}", msg)) |
| 37 |
})?; |
| 38 |
|
| 39 |
if self.max_window_size != 0 { |
| 40 |
self.dctx |
| 41 |
.set_max_window_size(self.max_window_size) |
| 42 |
.map_err(|msg| { |
| 43 |
ZstdError::new_err(format!("unable to set max window size: {}", msg)) |
| 44 |
})?; |
| 45 |
} |
| 46 |
|
| 47 |
self.dctx |
| 48 |
.set_format(self.format) |
| 49 |
.map_err(|msg| ZstdError::new_err(format!("unable to set decoding format: {}", msg)))?; |
| 50 |
|
| 51 |
if let Some(dict_data) = &self.dict_data { |
| 52 |
if load_dict { |
| 53 |
dict_data.try_borrow_mut(py)?.load_into_dctx(&self.dctx)?; |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
Ok(()) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
#[pymethods] |
| 62 |
impl ZstdDecompressor { |
| 63 |
#[new] |
| 64 |
#[pyo3(signature = (dict_data=None, max_window_size=0, format=0))] |
| 65 |
fn new( |
| 66 |
dict_data: Option<Py<ZstdCompressionDict>>, |
| 67 |
max_window_size: usize, |
| 68 |
format: u32, |
| 69 |
) -> PyResult<Self> { |
| 70 |
let format = if format == zstd_sys::ZSTD_format_e::ZSTD_f_zstd1 as _ { |
| 71 |
zstd_sys::ZSTD_format_e::ZSTD_f_zstd1 |
| 72 |
} else if format == zstd_sys::ZSTD_format_e::ZSTD_f_zstd1_magicless as _ { |
| 73 |
zstd_sys::ZSTD_format_e::ZSTD_f_zstd1_magicless |
| 74 |
} else { |
| 75 |
return Err(PyValueError::new_err(format!("invalid format value"))); |
| 76 |
}; |
| 77 |
|
| 78 |
let dctx = Arc::new(DCtx::new().map_err(|_| PyMemoryError::new_err(()))?); |
| 79 |
|
| 80 |
Ok(Self { |
| 81 |
dict_data, |
| 82 |
max_window_size, |
| 83 |
format, |
| 84 |
dctx, |
| 85 |
}) |
| 86 |
} |
| 87 |
|
| 88 |
#[pyo3(signature = (ifh, ofh, read_size=None, write_size=None))] |
| 89 |
fn copy_stream( |
| 90 |
&self, |
| 91 |
py: Python, |
| 92 |
ifh: &Bound<'_, PyAny>, |
| 93 |
ofh: &Bound<'_, PyAny>, |
| 94 |
read_size: Option<usize>, |
| 95 |
write_size: Option<usize>, |
| 96 |
) -> PyResult<(usize, usize)> { |
| 97 |
let read_size = read_size.unwrap_or_else(|| zstd_safe::DCtx::in_size()); |
| 98 |
let write_size = write_size.unwrap_or_else(|| zstd_safe::DCtx::out_size()); |
| 99 |
|
| 100 |
if !ifh.hasattr("read")? { |
| 101 |
return Err(PyValueError::new_err( |
| 102 |
"first argument must have a read() method", |
| 103 |
)); |
| 104 |
} |
| 105 |
|
| 106 |
if !ofh.hasattr("write")? { |
| 107 |
return Err(PyValueError::new_err( |
| 108 |
"second argument must have a write() method", |
| 109 |
)); |
| 110 |
} |
| 111 |
|
| 112 |
self.setup_dctx(py, true)?; |
| 113 |
|
| 114 |
let mut dest_buffer: Vec<u8> = Vec::with_capacity(write_size); |
| 115 |
|
| 116 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 117 |
src: std::ptr::null(), |
| 118 |
size: 0, |
| 119 |
pos: 0, |
| 120 |
}; |
| 121 |
|
| 122 |
let mut total_read = 0; |
| 123 |
let mut total_write = 0; |
| 124 |
|
| 125 |
// Read all available input. |
| 126 |
loop { |
| 127 |
let read_object = ifh.call_method1("read", (read_size,))?; |
| 128 |
let read_bytes = read_object.downcast::<PyBytes>()?; |
| 129 |
let read_data = read_bytes.as_bytes(); |
| 130 |
|
| 131 |
if read_data.len() == 0 { |
| 132 |
break; |
| 133 |
} |
| 134 |
|
| 135 |
total_read += read_data.len(); |
| 136 |
|
| 137 |
in_buffer.src = read_data.as_ptr() as *const _; |
| 138 |
in_buffer.size = read_data.len(); |
| 139 |
in_buffer.pos = 0; |
| 140 |
|
| 141 |
// Flush all read data to output. |
| 142 |
while in_buffer.pos < in_buffer.size { |
| 143 |
self.dctx |
| 144 |
.decompress_into_vec(&mut dest_buffer, &mut in_buffer) |
| 145 |
.map_err(|msg| ZstdError::new_err(format!("zstd decompress error: {}", msg)))?; |
| 146 |
|
| 147 |
if !dest_buffer.is_empty() { |
| 148 |
// TODO avoid buffer copy. |
| 149 |
let data = PyBytes::new_bound(py, &dest_buffer); |
| 150 |
|
| 151 |
ofh.call_method1("write", (data,))?; |
| 152 |
total_write += dest_buffer.len(); |
| 153 |
dest_buffer.clear(); |
| 154 |
} |
| 155 |
} |
| 156 |
// Continue loop to keep reading. |
| 157 |
} |
| 158 |
|
| 159 |
Ok((total_read, total_write)) |
| 160 |
} |
| 161 |
|
| 162 |
#[pyo3(signature = (buffer, max_output_size=0, read_across_frames=false, allow_extra_data=true))] |
| 163 |
fn decompress<'p>( |
| 164 |
&mut self, |
| 165 |
py: Python<'p>, |
| 166 |
buffer: PyBuffer<u8>, |
| 167 |
max_output_size: usize, |
| 168 |
read_across_frames: bool, |
| 169 |
allow_extra_data: bool, |
| 170 |
) -> PyResult<Bound<'p, PyBytes>> { |
| 171 |
if read_across_frames { |
| 172 |
return Err(ZstdError::new_err( |
| 173 |
"ZstdDecompressor.read_across_frames=True is not yet implemented", |
| 174 |
)); |
| 175 |
} |
| 176 |
|
| 177 |
self.setup_dctx(py, true)?; |
| 178 |
|
| 179 |
let output_size = |
| 180 |
unsafe { zstd_sys::ZSTD_getFrameContentSize(buffer.buf_ptr(), buffer.len_bytes()) }; |
| 181 |
|
| 182 |
let (output_buffer_size, output_size) = |
| 183 |
if output_size == zstd_sys::ZSTD_CONTENTSIZE_ERROR as _ { |
| 184 |
return Err(ZstdError::new_err( |
| 185 |
"error determining content size from frame header", |
| 186 |
)); |
| 187 |
} else if output_size == 0 { |
| 188 |
return Ok(PyBytes::new_bound(py, &[])); |
| 189 |
} else if output_size == zstd_sys::ZSTD_CONTENTSIZE_UNKNOWN as _ { |
| 190 |
if max_output_size == 0 { |
| 191 |
return Err(ZstdError::new_err( |
| 192 |
"could not determine content size in frame header", |
| 193 |
)); |
| 194 |
} |
| 195 |
|
| 196 |
(max_output_size, 0) |
| 197 |
} else { |
| 198 |
(output_size as _, output_size) |
| 199 |
}; |
| 200 |
|
| 201 |
let mut dest_buffer: Vec<u8> = Vec::new(); |
| 202 |
dest_buffer |
| 203 |
.try_reserve_exact(output_buffer_size) |
| 204 |
.map_err(|_| PyMemoryError::new_err(()))?; |
| 205 |
|
| 206 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 207 |
src: buffer.buf_ptr(), |
| 208 |
size: buffer.len_bytes(), |
| 209 |
pos: 0, |
| 210 |
}; |
| 211 |
|
| 212 |
let zresult = self |
| 213 |
.dctx |
| 214 |
.decompress_into_vec(&mut dest_buffer, &mut in_buffer) |
| 215 |
.map_err(|msg| ZstdError::new_err(format!("decompression error: {}", msg)))?; |
| 216 |
|
| 217 |
if zresult != 0 { |
| 218 |
Err(ZstdError::new_err( |
| 219 |
"decompression error: did not decompress full frame", |
| 220 |
)) |
| 221 |
} else if output_size != 0 && dest_buffer.len() != output_size as _ { |
| 222 |
Err(ZstdError::new_err(format!( |
| 223 |
"decompression error: decompressed {} bytes; expected {}", |
| 224 |
zresult, output_size |
| 225 |
))) |
| 226 |
} else if !allow_extra_data && in_buffer.pos < in_buffer.size { |
| 227 |
Err(ZstdError::new_err(format!( |
| 228 |
"compressed input contains {} bytes of unused data, which is disallowed", |
| 229 |
in_buffer.size - in_buffer.pos |
| 230 |
))) |
| 231 |
} else { |
| 232 |
// TODO avoid memory copy |
| 233 |
Ok(PyBytes::new_bound(py, &dest_buffer)) |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
fn decompress_content_dict_chain<'p>( |
| 238 |
&self, |
| 239 |
py: Python<'p>, |
| 240 |
frames: &Bound<'_, PyList>, |
| 241 |
) -> PyResult<Bound<'p, PyBytes>> { |
| 242 |
if frames.is_empty() { |
| 243 |
return Err(PyValueError::new_err("empty input chain")); |
| 244 |
} |
| 245 |
|
| 246 |
// First chunk should not be using a dictionary. We handle it specially. |
| 247 |
let chunk = frames.get_item(0)?; |
| 248 |
|
| 249 |
if !chunk.is_instance_of::<PyBytes>() { |
| 250 |
return Err(PyValueError::new_err("chunk 0 must be bytes")); |
| 251 |
} |
| 252 |
|
| 253 |
let chunk_buffer: PyBuffer<u8> = PyBuffer::get_bound(&chunk.as_borrowed())?; |
| 254 |
let mut params = zstd_sys::ZSTD_frameHeader { |
| 255 |
frameContentSize: 0, |
| 256 |
windowSize: 0, |
| 257 |
blockSizeMax: 0, |
| 258 |
frameType: zstd_sys::ZSTD_frameType_e::ZSTD_frame, |
| 259 |
headerSize: 0, |
| 260 |
dictID: 0, |
| 261 |
checksumFlag: 0, |
| 262 |
_reserved1: 0, |
| 263 |
_reserved2: 0, |
| 264 |
}; |
| 265 |
let zresult = unsafe { |
| 266 |
zstd_sys::ZSTD_getFrameHeader( |
| 267 |
&mut params, |
| 268 |
chunk_buffer.buf_ptr() as *const _, |
| 269 |
chunk_buffer.len_bytes(), |
| 270 |
) |
| 271 |
}; |
| 272 |
if unsafe { zstd_sys::ZSTD_isError(zresult) } != 0 { |
| 273 |
return Err(PyValueError::new_err("chunk 0 is not a valid zstd frame")); |
| 274 |
} else if zresult != 0 { |
| 275 |
return Err(PyValueError::new_err( |
| 276 |
"chunk 0 is too small to contain a zstd frame", |
| 277 |
)); |
| 278 |
} |
| 279 |
|
| 280 |
if params.frameContentSize == zstd_safe::CONTENTSIZE_UNKNOWN { |
| 281 |
return Err(PyValueError::new_err( |
| 282 |
"chunk 0 missing content size in frame", |
| 283 |
)); |
| 284 |
} |
| 285 |
|
| 286 |
self.setup_dctx(py, false)?; |
| 287 |
|
| 288 |
let mut last_buffer: Vec<u8> = Vec::with_capacity(params.frameContentSize as _); |
| 289 |
|
| 290 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 291 |
src: chunk_buffer.buf_ptr() as *mut _, |
| 292 |
size: chunk_buffer.len_bytes(), |
| 293 |
pos: 0, |
| 294 |
}; |
| 295 |
|
| 296 |
let zresult = self |
| 297 |
.dctx |
| 298 |
.decompress_into_vec(&mut last_buffer, &mut in_buffer) |
| 299 |
.map_err(|msg| ZstdError::new_err(format!("could not decompress chunk 0: {}", msg)))?; |
| 300 |
|
| 301 |
if zresult != 0 { |
| 302 |
return Err(ZstdError::new_err("chunk 0 did not decompress full frame")); |
| 303 |
} |
| 304 |
|
| 305 |
// Special case of chain length 1. |
| 306 |
if frames.len() == 1 { |
| 307 |
// TODO avoid buffer copy. |
| 308 |
let chunk = PyBytes::new_bound(py, &last_buffer); |
| 309 |
return Ok(chunk); |
| 310 |
} |
| 311 |
|
| 312 |
for (i, chunk) in frames.iter().enumerate().skip(1) { |
| 313 |
if !chunk.is_instance_of::<PyBytes>() { |
| 314 |
return Err(PyValueError::new_err(format!("chunk {} must be bytes", i))); |
| 315 |
} |
| 316 |
|
| 317 |
let chunk_buffer: PyBuffer<u8> = PyBuffer::get_bound(&chunk.as_borrowed())?; |
| 318 |
|
| 319 |
let zresult = unsafe { |
| 320 |
zstd_sys::ZSTD_getFrameHeader( |
| 321 |
&mut params as *mut _, |
| 322 |
chunk_buffer.buf_ptr(), |
| 323 |
chunk_buffer.len_bytes(), |
| 324 |
) |
| 325 |
}; |
| 326 |
if unsafe { zstd_sys::ZSTD_isError(zresult) } != 0 { |
| 327 |
return Err(PyValueError::new_err(format!( |
| 328 |
"chunk {} is not a valid zstd frame", |
| 329 |
i |
| 330 |
))); |
| 331 |
} else if zresult != 0 { |
| 332 |
return Err(PyValueError::new_err(format!( |
| 333 |
"chunk {} is too small to contain a zstd frame", |
| 334 |
i |
| 335 |
))); |
| 336 |
} |
| 337 |
|
| 338 |
if params.frameContentSize == zstd_safe::CONTENTSIZE_UNKNOWN { |
| 339 |
return Err(PyValueError::new_err(format!( |
| 340 |
"chunk {} missing content size in frame", |
| 341 |
i |
| 342 |
))); |
| 343 |
} |
| 344 |
|
| 345 |
let mut dest_buffer: Vec<u8> = Vec::with_capacity(params.frameContentSize as _); |
| 346 |
|
| 347 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 348 |
src: chunk_buffer.buf_ptr(), |
| 349 |
size: chunk_buffer.len_bytes(), |
| 350 |
pos: 0, |
| 351 |
}; |
| 352 |
|
| 353 |
let zresult = self |
| 354 |
.dctx |
| 355 |
.decompress_into_vec(&mut dest_buffer, &mut in_buffer) |
| 356 |
.map_err(|msg| { |
| 357 |
ZstdError::new_err(format!("could not decompress chunk {}: {}", i, msg)) |
| 358 |
})?; |
| 359 |
|
| 360 |
if zresult != 0 { |
| 361 |
return Err(ZstdError::new_err(format!( |
| 362 |
"chunk {} did not decompress full frame", |
| 363 |
i |
| 364 |
))); |
| 365 |
} |
| 366 |
|
| 367 |
last_buffer = dest_buffer; |
| 368 |
} |
| 369 |
|
| 370 |
// TODO avoid buffer copy. |
| 371 |
Ok(PyBytes::new_bound(py, &last_buffer)) |
| 372 |
} |
| 373 |
|
| 374 |
#[pyo3(signature = (write_size=None, read_across_frames=false))] |
| 375 |
fn decompressobj( |
| 376 |
&self, |
| 377 |
py: Python, |
| 378 |
write_size: Option<usize>, |
| 379 |
read_across_frames: bool, |
| 380 |
) -> PyResult<ZstdDecompressionObj> { |
| 381 |
if let Some(write_size) = write_size { |
| 382 |
if write_size < 1 { |
| 383 |
return Err(PyValueError::new_err("write_size must be positive")); |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
let write_size = write_size.unwrap_or_else(|| zstd_safe::DCtx::out_size()); |
| 388 |
|
| 389 |
self.setup_dctx(py, true)?; |
| 390 |
|
| 391 |
ZstdDecompressionObj::new(self.dctx.clone(), write_size, read_across_frames) |
| 392 |
} |
| 393 |
|
| 394 |
fn memory_size(&self) -> usize { |
| 395 |
self.dctx.memory_size() |
| 396 |
} |
| 397 |
|
| 398 |
#[pyo3(signature = (frames, decompressed_sizes=None, threads=0))] |
| 399 |
#[allow(unused_variables)] |
| 400 |
fn multi_decompress_to_buffer( |
| 401 |
&self, |
| 402 |
py: Python, |
| 403 |
frames: &Bound<'_, PyAny>, |
| 404 |
decompressed_sizes: Option<&Bound<'_, PyAny>>, |
| 405 |
threads: isize, |
| 406 |
) -> PyResult<ZstdBufferWithSegmentsCollection> { |
| 407 |
self.setup_dctx(py, true)?; |
| 408 |
|
| 409 |
multi_decompress_to_buffer( |
| 410 |
py, |
| 411 |
self.dict_data.as_ref(), |
| 412 |
frames, |
| 413 |
decompressed_sizes, |
| 414 |
threads, |
| 415 |
) |
| 416 |
} |
| 417 |
|
| 418 |
#[pyo3(signature = (reader, read_size=None, write_size=None, skip_bytes=None))] |
| 419 |
fn read_to_iter( |
| 420 |
&self, |
| 421 |
py: Python, |
| 422 |
reader: &Bound<'_, PyAny>, |
| 423 |
read_size: Option<usize>, |
| 424 |
write_size: Option<usize>, |
| 425 |
skip_bytes: Option<usize>, |
| 426 |
) -> PyResult<ZstdDecompressorIterator> { |
| 427 |
let read_size = read_size.unwrap_or_else(|| zstd_safe::DCtx::in_size()); |
| 428 |
let write_size = write_size.unwrap_or_else(|| zstd_safe::DCtx::out_size()); |
| 429 |
let skip_bytes = skip_bytes.unwrap_or(0); |
| 430 |
|
| 431 |
if skip_bytes >= read_size { |
| 432 |
return Err(PyValueError::new_err( |
| 433 |
"skip_bytes must be smaller than read_size", |
| 434 |
)); |
| 435 |
} |
| 436 |
|
| 437 |
if !reader.hasattr("read")? && !reader.hasattr("__getitem__")? { |
| 438 |
return Err(PyValueError::new_err( |
| 439 |
"must pass an object with a read() method or conforms to buffer protocol", |
| 440 |
)); |
| 441 |
} |
| 442 |
|
| 443 |
self.setup_dctx(py, true)?; |
| 444 |
|
| 445 |
ZstdDecompressorIterator::new( |
| 446 |
py, |
| 447 |
self.dctx.clone(), |
| 448 |
reader, |
| 449 |
read_size, |
| 450 |
write_size, |
| 451 |
skip_bytes, |
| 452 |
) |
| 453 |
} |
| 454 |
|
| 455 |
#[pyo3(signature = (source, read_size=None, read_across_frames=false, closefd=true))] |
| 456 |
fn stream_reader( |
| 457 |
&self, |
| 458 |
py: Python, |
| 459 |
source: &Bound<'_, PyAny>, |
| 460 |
read_size: Option<usize>, |
| 461 |
read_across_frames: bool, |
| 462 |
closefd: bool, |
| 463 |
) -> PyResult<ZstdDecompressionReader> { |
| 464 |
let read_size = read_size.unwrap_or_else(|| zstd_safe::DCtx::in_size()); |
| 465 |
|
| 466 |
self.setup_dctx(py, true)?; |
| 467 |
|
| 468 |
ZstdDecompressionReader::new( |
| 469 |
py, |
| 470 |
self.dctx.clone(), |
| 471 |
source, |
| 472 |
read_size, |
| 473 |
read_across_frames, |
| 474 |
closefd, |
| 475 |
) |
| 476 |
} |
| 477 |
|
| 478 |
#[pyo3(signature = (writer, write_size=None, write_return_read=true, closefd=true))] |
| 479 |
fn stream_writer( |
| 480 |
&self, |
| 481 |
py: Python, |
| 482 |
writer: &Bound<'_, PyAny>, |
| 483 |
write_size: Option<usize>, |
| 484 |
write_return_read: bool, |
| 485 |
closefd: bool, |
| 486 |
) -> PyResult<ZstdDecompressionWriter> { |
| 487 |
let write_size = write_size.unwrap_or_else(|| zstd_safe::DCtx::out_size()); |
| 488 |
|
| 489 |
self.setup_dctx(py, true)?; |
| 490 |
|
| 491 |
ZstdDecompressionWriter::new( |
| 492 |
py, |
| 493 |
self.dctx.clone(), |
| 494 |
writer, |
| 495 |
write_size, |
| 496 |
write_return_read, |
| 497 |
closefd, |
| 498 |
) |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
#[pyfunction] |
| 503 |
fn estimate_decompression_context_size() -> usize { |
| 504 |
unsafe { zstd_sys::ZSTD_estimateDCtxSize() } |
| 505 |
} |
| 506 |
|
| 507 |
pub(crate) fn init_module(module: &Bound<'_, PyModule>) -> PyResult<()> { |
| 508 |
module.add_class::<ZstdDecompressor>()?; |
| 509 |
module.add_function(wrap_pyfunction!( |
| 510 |
estimate_decompression_context_size, |
| 511 |
module |
| 512 |
)?)?; |
| 513 |
|
| 514 |
Ok(()) |
| 515 |
} |