| 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::{prelude::*, types::PyBytes, IntoPyObjectExt}, |
| 14 |
std::sync::Arc, |
| 15 |
}; |
| 16 |
|
| 17 |
#[pyclass(module = "zstandard.backend_rust")] |
| 18 |
pub struct ZstdCompressionChunker { |
| 19 |
cctx: Arc<CCtx<'static>>, |
| 20 |
chunk_size: usize, |
| 21 |
finished: bool, |
| 22 |
iterator: Option<Py<ZstdCompressionChunkerIterator>>, |
| 23 |
partial_buffer: Option<Vec<u8>>, |
| 24 |
} |
| 25 |
|
| 26 |
unsafe impl Sync for ZstdCompressionChunker {} |
| 27 |
|
| 28 |
impl ZstdCompressionChunker { |
| 29 |
pub fn new(cctx: Arc<CCtx<'static>>, chunk_size: usize) -> PyResult<Self> { |
| 30 |
Ok(Self { |
| 31 |
cctx, |
| 32 |
chunk_size, |
| 33 |
finished: false, |
| 34 |
iterator: None, |
| 35 |
partial_buffer: None, |
| 36 |
}) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
impl ZstdCompressionChunker { |
| 41 |
fn ensure_state(&mut self, py: Python) { |
| 42 |
if let Some(it) = &self.iterator { |
| 43 |
if it.borrow(py).finished { |
| 44 |
if it.borrow(py).mode == IteratorMode::Finish { |
| 45 |
self.finished = true; |
| 46 |
} |
| 47 |
|
| 48 |
if !it.borrow(py).dest_buffer.is_empty() { |
| 49 |
// TODO can we avoid the memory copy? |
| 50 |
// Vec.clone() won't preserve the capacity of the source. |
| 51 |
// So we create a new Vec with desired capacity and copy to it. |
| 52 |
// This is strictly better than a clone + resize. |
| 53 |
let mut dest_buffer = Vec::with_capacity(self.chunk_size); |
| 54 |
unsafe { |
| 55 |
dest_buffer.set_len(it.borrow(py).dest_buffer.len()); |
| 56 |
} |
| 57 |
dest_buffer.copy_from_slice(it.borrow(py).dest_buffer.as_slice()); |
| 58 |
self.partial_buffer = Some(dest_buffer); |
| 59 |
} |
| 60 |
|
| 61 |
self.iterator = None; |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
fn get_dest_buffer(&mut self) -> Vec<u8> { |
| 67 |
self.partial_buffer |
| 68 |
.take() |
| 69 |
.unwrap_or_else(|| Vec::with_capacity(self.chunk_size)) |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
#[pymethods] |
| 74 |
impl ZstdCompressionChunker { |
| 75 |
fn compress( |
| 76 |
&mut self, |
| 77 |
py: Python, |
| 78 |
data: &Bound<'_, PyAny>, |
| 79 |
) -> PyResult<Py<ZstdCompressionChunkerIterator>> { |
| 80 |
self.ensure_state(py); |
| 81 |
|
| 82 |
if self.finished { |
| 83 |
return Err(ZstdError::new_err( |
| 84 |
"cannot call compress() after compression finished", |
| 85 |
)); |
| 86 |
} |
| 87 |
|
| 88 |
let source = make_in_buffer_source(py, data, zstd_safe::CCtx::in_size())?; |
| 89 |
|
| 90 |
let it = Bound::new( |
| 91 |
py, |
| 92 |
ZstdCompressionChunkerIterator { |
| 93 |
cctx: self.cctx.clone(), |
| 94 |
source, |
| 95 |
mode: IteratorMode::Normal, |
| 96 |
dest_buffer: self.get_dest_buffer(), |
| 97 |
finished: false, |
| 98 |
}, |
| 99 |
)?; |
| 100 |
|
| 101 |
self.iterator = Some(it.clone().unbind()); |
| 102 |
|
| 103 |
Ok(it.unbind()) |
| 104 |
} |
| 105 |
|
| 106 |
fn flush<'p>(&mut self, py: Python<'p>) -> PyResult<Py<ZstdCompressionChunkerIterator>> { |
| 107 |
self.ensure_state(py); |
| 108 |
|
| 109 |
if self.finished { |
| 110 |
return Err(ZstdError::new_err( |
| 111 |
"cannot call flush() after compression finished", |
| 112 |
)); |
| 113 |
} |
| 114 |
|
| 115 |
if self.iterator.is_some() { |
| 116 |
return Err(ZstdError::new_err( |
| 117 |
"cannot call flush() before consuming output from previous operation", |
| 118 |
)); |
| 119 |
} |
| 120 |
|
| 121 |
let source = make_in_buffer_source(py, &PyBytes::new(py, &[]), zstd_safe::CCtx::in_size())?; |
| 122 |
|
| 123 |
let it = Bound::new( |
| 124 |
py, |
| 125 |
ZstdCompressionChunkerIterator { |
| 126 |
cctx: self.cctx.clone(), |
| 127 |
source, |
| 128 |
mode: IteratorMode::Flush, |
| 129 |
dest_buffer: self.get_dest_buffer(), |
| 130 |
finished: false, |
| 131 |
}, |
| 132 |
)?; |
| 133 |
|
| 134 |
self.iterator = Some(it.clone().unbind()); |
| 135 |
|
| 136 |
Ok(it.unbind()) |
| 137 |
} |
| 138 |
|
| 139 |
fn finish<'p>(&mut self, py: Python<'p>) -> PyResult<Py<ZstdCompressionChunkerIterator>> { |
| 140 |
self.ensure_state(py); |
| 141 |
|
| 142 |
if self.finished { |
| 143 |
return Err(ZstdError::new_err( |
| 144 |
"cannot call finish() after compression finished", |
| 145 |
)); |
| 146 |
} |
| 147 |
|
| 148 |
if self.iterator.is_some() { |
| 149 |
return Err(ZstdError::new_err( |
| 150 |
"cannot call finish() before consuming output from previous operation", |
| 151 |
)); |
| 152 |
} |
| 153 |
|
| 154 |
let source = make_in_buffer_source(py, &PyBytes::new(py, &[]), zstd_safe::CCtx::in_size())?; |
| 155 |
|
| 156 |
let it = Bound::new( |
| 157 |
py, |
| 158 |
ZstdCompressionChunkerIterator { |
| 159 |
cctx: self.cctx.clone(), |
| 160 |
source, |
| 161 |
mode: IteratorMode::Finish, |
| 162 |
dest_buffer: self.get_dest_buffer(), |
| 163 |
finished: false, |
| 164 |
}, |
| 165 |
)?; |
| 166 |
|
| 167 |
self.iterator = Some(it.clone().unbind()); |
| 168 |
|
| 169 |
Ok(it.unbind()) |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
#[derive(Debug, PartialEq)] |
| 174 |
enum IteratorMode { |
| 175 |
Normal, |
| 176 |
Flush, |
| 177 |
Finish, |
| 178 |
} |
| 179 |
|
| 180 |
#[pyclass(module = "zstandard.backend_rust")] |
| 181 |
struct ZstdCompressionChunkerIterator { |
| 182 |
cctx: Arc<CCtx<'static>>, |
| 183 |
source: Box<dyn InBufferSource + Send>, |
| 184 |
mode: IteratorMode, |
| 185 |
dest_buffer: Vec<u8>, |
| 186 |
finished: bool, |
| 187 |
} |
| 188 |
|
| 189 |
unsafe impl Sync for ZstdCompressionChunkerIterator {} |
| 190 |
|
| 191 |
#[pymethods] |
| 192 |
impl ZstdCompressionChunkerIterator { |
| 193 |
// PyIterProtocol. |
| 194 |
|
| 195 |
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> { |
| 196 |
slf |
| 197 |
} |
| 198 |
|
| 199 |
fn __next__(mut slf: PyRefMut<Self>) -> PyResult<Option<PyObject>> { |
| 200 |
if slf.finished { |
| 201 |
return Ok(None); |
| 202 |
} |
| 203 |
|
| 204 |
let py = unsafe { Python::assume_gil_acquired() }; |
| 205 |
|
| 206 |
// Consume any data left in the input. |
| 207 |
while let Some(mut in_buffer) = slf.source.input_buffer(py)? { |
| 208 |
let old_pos = in_buffer.pos; |
| 209 |
|
| 210 |
slf.cctx |
| 211 |
.clone() |
| 212 |
.compress_into_vec( |
| 213 |
&mut slf.dest_buffer, |
| 214 |
&mut in_buffer, |
| 215 |
zstd_sys::ZSTD_EndDirective::ZSTD_e_continue, |
| 216 |
) |
| 217 |
.map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?; |
| 218 |
|
| 219 |
slf.source.record_bytes_read(in_buffer.pos - old_pos); |
| 220 |
|
| 221 |
// If we produced a full output chunk, emit it. |
| 222 |
if slf.dest_buffer.len() == slf.dest_buffer.capacity() { |
| 223 |
let chunk = PyBytes::new(py, &slf.dest_buffer); |
| 224 |
slf.dest_buffer.clear(); |
| 225 |
|
| 226 |
return Ok(Some(chunk.into_py_any(py)?)); |
| 227 |
} |
| 228 |
|
| 229 |
// Else continue to compress available input data. |
| 230 |
continue; |
| 231 |
} |
| 232 |
|
| 233 |
// No more input data. A partial chunk may be in the destination |
| 234 |
// buffer. If we're in normal compression mode, we're done. Otherwise |
| 235 |
// if we're in flush or finish mode, we need to emit what data remains. |
| 236 |
|
| 237 |
let flush_mode = match slf.mode { |
| 238 |
IteratorMode::Normal => { |
| 239 |
slf.finished = true; |
| 240 |
return Ok(None); |
| 241 |
} |
| 242 |
IteratorMode::Flush => zstd_sys::ZSTD_EndDirective::ZSTD_e_flush, |
| 243 |
IteratorMode::Finish => zstd_sys::ZSTD_EndDirective::ZSTD_e_end, |
| 244 |
}; |
| 245 |
|
| 246 |
let mut in_buffer = zstd_sys::ZSTD_inBuffer { |
| 247 |
src: std::ptr::null(), |
| 248 |
size: 0, |
| 249 |
pos: 0, |
| 250 |
}; |
| 251 |
|
| 252 |
let zresult = slf |
| 253 |
.cctx |
| 254 |
.clone() |
| 255 |
.compress_into_vec(&mut slf.dest_buffer, &mut in_buffer, flush_mode) |
| 256 |
.map_err(|msg| ZstdError::new_err(format!("zstd compress error: {}", msg)))?; |
| 257 |
|
| 258 |
// When flushing or finishing, we always emit data in the output |
| 259 |
// buffer. But the operation could fill the output buffer and not be |
| 260 |
// finished. |
| 261 |
|
| 262 |
// If we didn't emit anything to the output buffer, we must be finished. |
| 263 |
// Update state and stop iteration. |
| 264 |
if slf.dest_buffer.is_empty() { |
| 265 |
slf.finished = true; |
| 266 |
return Ok(None); |
| 267 |
} |
| 268 |
|
| 269 |
// If the flush or finish didn't fill the output buffer, we must |
| 270 |
// be done. |
| 271 |
// If compressor said operation is finished, we are also done. |
| 272 |
if zresult == 0 || slf.dest_buffer.len() < slf.dest_buffer.capacity() { |
| 273 |
slf.finished = true; |
| 274 |
} |
| 275 |
|
| 276 |
let chunk = PyBytes::new(py, &slf.dest_buffer); |
| 277 |
slf.dest_buffer.clear(); |
| 278 |
|
| 279 |
Ok(Some(chunk.into_py_any(py)?)) |
| 280 |
} |
| 281 |
} |