| 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::{BufferSegment, ZstdBufferWithSegments, ZstdBufferWithSegmentsCollection}, |
| 10 |
compression_dict::ZstdCompressionDict, |
| 11 |
exceptions::ZstdError, |
| 12 |
zstd_safe::DCtx, |
| 13 |
}, |
| 14 |
pyo3::{ |
| 15 |
buffer::PyBuffer, |
| 16 |
exceptions::{PyTypeError, PyValueError}, |
| 17 |
prelude::*, |
| 18 |
types::{PyBytes, PyList, PyTuple}, |
| 19 |
}, |
| 20 |
rayon::prelude::*, |
| 21 |
}; |
| 22 |
|
| 23 |
struct DataSource<'a> { |
| 24 |
data: &'a [u8], |
| 25 |
decompressed_size: usize, |
| 26 |
} |
| 27 |
|
| 28 |
pub fn multi_decompress_to_buffer( |
| 29 |
py: Python, |
| 30 |
dict_data: Option<&Py<ZstdCompressionDict>>, |
| 31 |
frames: &Bound<'_, PyAny>, |
| 32 |
decompressed_sizes: Option<&Bound<'_, PyAny>>, |
| 33 |
threads: isize, |
| 34 |
) -> PyResult<ZstdBufferWithSegmentsCollection> { |
| 35 |
let threads = if threads < 0 { |
| 36 |
num_cpus::get() |
| 37 |
} else if threads < 2 { |
| 38 |
1 |
| 39 |
} else { |
| 40 |
threads as _ |
| 41 |
}; |
| 42 |
|
| 43 |
let frame_sizes: &[u64] = if let Some(frames_sizes) = decompressed_sizes { |
| 44 |
let buffer: PyBuffer<u8> = PyBuffer::get(&frames_sizes.as_borrowed())?; |
| 45 |
unsafe { std::slice::from_raw_parts(buffer.buf_ptr() as *const _, buffer.len_bytes() / 8) } |
| 46 |
} else { |
| 47 |
&[] |
| 48 |
}; |
| 49 |
|
| 50 |
let mut sources = vec![]; |
| 51 |
|
| 52 |
if let Ok(buffer) = frames.downcast::<ZstdBufferWithSegments>() { |
| 53 |
if decompressed_sizes.is_some() && frame_sizes.len() != buffer.len()? { |
| 54 |
return Err(PyValueError::new_err(format!( |
| 55 |
"decompressed_sizes size mismatch; expected {}, got {}", |
| 56 |
buffer.len()?, |
| 57 |
frame_sizes.len() |
| 58 |
))); |
| 59 |
} |
| 60 |
|
| 61 |
let borrow = buffer.borrow(); |
| 62 |
|
| 63 |
sources.reserve_exact(borrow.segments.len()); |
| 64 |
|
| 65 |
for i in 0..borrow.segments.len() { |
| 66 |
let slice = borrow.get_segment_slice(py, i); |
| 67 |
|
| 68 |
sources.push(DataSource { |
| 69 |
data: slice, |
| 70 |
decompressed_size: *frame_sizes.get(i).unwrap_or(&0) as _, |
| 71 |
}); |
| 72 |
} |
| 73 |
} else if let Ok(collection) = frames.downcast::<ZstdBufferWithSegmentsCollection>() { |
| 74 |
let frames_count = collection.len()?; |
| 75 |
|
| 76 |
if decompressed_sizes.is_some() && frame_sizes.len() != frames_count { |
| 77 |
return Err(PyValueError::new_err(format!( |
| 78 |
"decompressed_sizes size mismatch; expected {}, got {}", |
| 79 |
frames_count, |
| 80 |
frame_sizes.len() |
| 81 |
))); |
| 82 |
} |
| 83 |
|
| 84 |
sources.reserve_exact(frames_count); |
| 85 |
|
| 86 |
let mut offset = 0; |
| 87 |
for buffer_obj in &collection.borrow().buffers { |
| 88 |
let buffer = buffer_obj.downcast_bound::<ZstdBufferWithSegments>(py)?; |
| 89 |
let borrow = buffer.borrow(); |
| 90 |
|
| 91 |
for i in 0..borrow.segments.len() { |
| 92 |
let slice = borrow.get_segment_slice(py, i); |
| 93 |
|
| 94 |
sources.push(DataSource { |
| 95 |
data: slice, |
| 96 |
decompressed_size: *frame_sizes.get(offset).unwrap_or(&0) as _, |
| 97 |
}); |
| 98 |
|
| 99 |
offset += 1; |
| 100 |
} |
| 101 |
} |
| 102 |
} else if let Ok(list) = frames.extract::<Bound<'_, PyList>>() { |
| 103 |
if decompressed_sizes.is_some() && frame_sizes.len() != list.len() { |
| 104 |
return Err(PyValueError::new_err(format!( |
| 105 |
"decompressed_sizes size mismatch; expected {}; got {}", |
| 106 |
list.len(), |
| 107 |
frame_sizes.len() |
| 108 |
))); |
| 109 |
} |
| 110 |
|
| 111 |
sources.reserve_exact(list.len()); |
| 112 |
|
| 113 |
for (i, item) in list.iter().enumerate() { |
| 114 |
let buffer: PyBuffer<u8> = PyBuffer::get(&item.as_borrowed()) |
| 115 |
.map_err(|_| PyTypeError::new_err(format!("item {} not a bytes like object", i)))?; |
| 116 |
|
| 117 |
let slice = unsafe { |
| 118 |
std::slice::from_raw_parts(buffer.buf_ptr() as *const _, buffer.len_bytes()) |
| 119 |
}; |
| 120 |
|
| 121 |
sources.push(DataSource { |
| 122 |
data: slice, |
| 123 |
decompressed_size: *frame_sizes.get(i).unwrap_or(&0) as _, |
| 124 |
}); |
| 125 |
} |
| 126 |
} else { |
| 127 |
return Err(PyTypeError::new_err( |
| 128 |
"argument must be list of BufferWithSegments", |
| 129 |
)); |
| 130 |
} |
| 131 |
|
| 132 |
decompress_from_datasources(py, dict_data, sources, threads) |
| 133 |
} |
| 134 |
|
| 135 |
#[derive(Debug, PartialEq)] |
| 136 |
enum WorkerError { |
| 137 |
None, |
| 138 |
NoSize, |
| 139 |
Zstd(&'static str), |
| 140 |
} |
| 141 |
|
| 142 |
/// Holds results of an individual compression operation. |
| 143 |
struct WorkerResult { |
| 144 |
source_offset: usize, |
| 145 |
error: WorkerError, |
| 146 |
data: Option<Vec<u8>>, |
| 147 |
} |
| 148 |
|
| 149 |
fn decompress_from_datasources( |
| 150 |
py: Python, |
| 151 |
dict_data: Option<&Py<ZstdCompressionDict>>, |
| 152 |
sources: Vec<DataSource>, |
| 153 |
thread_count: usize, |
| 154 |
) -> PyResult<ZstdBufferWithSegmentsCollection> { |
| 155 |
// More threads than inputs makes no sense. |
| 156 |
let thread_count = std::cmp::min(thread_count, sources.len()); |
| 157 |
|
| 158 |
// TODO lower thread count when input size is too small and threads |
| 159 |
// would add overhead. |
| 160 |
|
| 161 |
let mut dctxs = Vec::with_capacity(thread_count); |
| 162 |
let results = std::sync::Mutex::new(Vec::with_capacity(sources.len())); |
| 163 |
|
| 164 |
// TODO there are tons of inefficiencies in this implementation compared |
| 165 |
// to the C backend. |
| 166 |
|
| 167 |
for _ in 0..thread_count { |
| 168 |
let dctx = DCtx::new().map_err(ZstdError::new_err)?; |
| 169 |
|
| 170 |
if let Some(dict_data) = dict_data { |
| 171 |
dict_data.borrow_mut(py).load_into_dctx(&dctx)?; |
| 172 |
} |
| 173 |
|
| 174 |
dctxs.push(dctx); |
| 175 |
} |
| 176 |
|
| 177 |
let pool = rayon::ThreadPoolBuilder::new() |
| 178 |
.num_threads(thread_count) |
| 179 |
.build() |
| 180 |
.map_err(|err| ZstdError::new_err(format!("error initializing thread pool: {}", err)))?; |
| 181 |
|
| 182 |
pool.install(|| { |
| 183 |
sources |
| 184 |
.par_iter() |
| 185 |
.enumerate() |
| 186 |
.for_each(|(index, source): (usize, &DataSource)| { |
| 187 |
let thread_index = pool.current_thread_index().unwrap(); |
| 188 |
|
| 189 |
let dctx = &dctxs[thread_index]; |
| 190 |
|
| 191 |
let mut result = WorkerResult { |
| 192 |
source_offset: index, |
| 193 |
error: WorkerError::None, |
| 194 |
data: None, |
| 195 |
}; |
| 196 |
|
| 197 |
let decompressed_size = if source.decompressed_size == 0 { |
| 198 |
let frame_size = match zstd_safe::get_frame_content_size(source.data) { |
| 199 |
Err(zstd_safe::ContentSizeError) => { |
| 200 |
result.error = WorkerError::NoSize; |
| 201 |
zstd_safe::CONTENTSIZE_ERROR |
| 202 |
} |
| 203 |
Ok(None) => { |
| 204 |
result.error = WorkerError::NoSize; |
| 205 |
zstd_safe::CONTENTSIZE_UNKNOWN |
| 206 |
} |
| 207 |
Ok(Some(frame_size)) => frame_size, |
| 208 |
}; |
| 209 |
|
| 210 |
frame_size as _ |
| 211 |
} else { |
| 212 |
source.decompressed_size |
| 213 |
}; |
| 214 |
|
| 215 |
if result.error == WorkerError::None { |
| 216 |
let mut dest_buffer = Vec::with_capacity(decompressed_size); |
| 217 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 218 |
src: source.data.as_ptr() as *const _, |
| 219 |
size: source.data.len(), |
| 220 |
pos: 0, |
| 221 |
}; |
| 222 |
|
| 223 |
match dctx.decompress_into_vec(&mut dest_buffer, &mut in_buffer) { |
| 224 |
Ok(_) => { |
| 225 |
result.data = Some(dest_buffer); |
| 226 |
} |
| 227 |
Err(msg) => { |
| 228 |
result.error = WorkerError::Zstd(msg); |
| 229 |
} |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
results.lock().unwrap().push(result); |
| 234 |
}); |
| 235 |
}); |
| 236 |
|
| 237 |
// Need to sort results by their input order or else results aren't |
| 238 |
// deterministic. |
| 239 |
results |
| 240 |
.lock() |
| 241 |
.unwrap() |
| 242 |
.sort_by(|a, b| a.source_offset.cmp(&b.source_offset)); |
| 243 |
|
| 244 |
// TODO this is horribly inefficient due to memory copies. |
| 245 |
let els = PyTuple::new( |
| 246 |
py, |
| 247 |
results |
| 248 |
.lock() |
| 249 |
.unwrap() |
| 250 |
.iter() |
| 251 |
.map(|result| { |
| 252 |
match result.error { |
| 253 |
WorkerError::None => Ok(()), |
| 254 |
WorkerError::Zstd(msg) => Err(ZstdError::new_err(format!( |
| 255 |
"error decompressing item {}: {}", |
| 256 |
result.source_offset, msg |
| 257 |
))), |
| 258 |
WorkerError::NoSize => Err(PyValueError::new_err(format!( |
| 259 |
"could not determine decompressed size of item {}", |
| 260 |
result.source_offset |
| 261 |
))), |
| 262 |
}?; |
| 263 |
|
| 264 |
let data = result.data.as_ref().unwrap(); |
| 265 |
let chunk = PyBytes::new(py, data); |
| 266 |
let segments = vec![BufferSegment { |
| 267 |
offset: 0, |
| 268 |
length: data.len() as _, |
| 269 |
}]; |
| 270 |
|
| 271 |
let segments = unsafe { |
| 272 |
PyBytes::from_ptr( |
| 273 |
py, |
| 274 |
segments.as_ptr() as *const _, |
| 275 |
segments.len() * std::mem::size_of::<BufferSegment>(), |
| 276 |
) |
| 277 |
}; |
| 278 |
let segments_buffer = PyBuffer::get(&segments)?; |
| 279 |
|
| 280 |
Py::new( |
| 281 |
py, |
| 282 |
ZstdBufferWithSegments::new(py, &chunk, segments_buffer)?, |
| 283 |
) |
| 284 |
}) |
| 285 |
.collect::<PyResult<Vec<_>>>()?, |
| 286 |
)?; |
| 287 |
|
| 288 |
ZstdBufferWithSegmentsCollection::new(py, &els) |
| 289 |
} |