|
| 1 | +use pyo3::exceptions::PyValueError; |
| 2 | +use pyo3::prelude::*; |
| 3 | +use pyo3::types::{PyByteArray, PyBytes}; |
| 4 | + |
| 5 | +const MAX_DISCOVER_OUTPUT_SIZE: usize = 1024 * 1024 * 1024; |
| 6 | + |
| 7 | +#[pyfunction] |
| 8 | +#[pyo3(signature = (src, uncompressed_size=-1, return_bytearray=false))] |
| 9 | +fn decompress( |
| 10 | + py: Python<'_>, |
| 11 | + src: Vec<u8>, |
| 12 | + uncompressed_size: isize, |
| 13 | + return_bytearray: bool, |
| 14 | +) -> PyResult<PyObject> { |
| 15 | + let result = if uncompressed_size < 0 { |
| 16 | + // If the uncompressed size is not provided, we need to discover it first |
| 17 | + let mut output_size = lz4_flex::block::get_maximum_output_size(src.len()); |
| 18 | + loop { |
| 19 | + // If the output size is too large, we should not attempt to decompress further |
| 20 | + if output_size > MAX_DISCOVER_OUTPUT_SIZE { |
| 21 | + return Err(PyErr::new::<PyValueError, _>( |
| 22 | + "output size is too large".to_string(), |
| 23 | + )); |
| 24 | + } |
| 25 | + |
| 26 | + match lz4_flex::block::decompress(&src, output_size) { |
| 27 | + Ok(result) => { |
| 28 | + break result; |
| 29 | + } |
| 30 | + Err(lz4_flex::block::DecompressError::OutputTooSmall { |
| 31 | + expected, |
| 32 | + actual: _, |
| 33 | + }) => { |
| 34 | + output_size = expected; |
| 35 | + } |
| 36 | + Err(e) => { |
| 37 | + return Err(PyErr::new::<PyValueError, _>(e.to_string())); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } else { |
| 42 | + lz4_flex::block::decompress(&src, uncompressed_size as usize) |
| 43 | + .map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))? |
| 44 | + }; |
| 45 | + |
| 46 | + let pyresult = PyBytes::new_bound(py, &result); |
| 47 | + if return_bytearray { |
| 48 | + Ok(PyByteArray::from_bound(&pyresult)?.into()) |
| 49 | + } else { |
| 50 | + Ok(pyresult.into()) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +pub fn create_submodule(m: &Bound<'_, PyModule>) -> PyResult<()> { |
| 55 | + let submodule = PyModule::new_bound(m.py(), "lz4")?; |
| 56 | + submodule.add_function(wrap_pyfunction!(decompress, m)?)?; |
| 57 | + m.add_submodule(&submodule) |
| 58 | +} |
0 commit comments