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