|
| 1 | +// spell-checker:ignore chunker libbz |
| 2 | +//! VM-independent bzip2 stream engine. |
| 3 | +//! |
| 4 | +//! The engine owns its native stream state and reports plain Rust errors so |
| 5 | +//! interpreter and embedding layers can provide their own object and exception |
| 6 | +//! adapters. |
| 7 | +
|
| 8 | +use bzip2::{Action, Compress, Compression, Decompress, Error, Status}; |
| 9 | + |
| 10 | +use super::Chunker; |
| 11 | + |
| 12 | +const INITIAL_BUFFER_SIZE: usize = 8192; |
| 13 | +const BIGCHUNK: usize = 512 * 1024; |
| 14 | + |
| 15 | +/// Double the output block until `BIGCHUNK`, then keep the size fixed. |
| 16 | +const fn new_buffer_size(current_size: usize) -> usize { |
| 17 | + if current_size < BIGCHUNK { |
| 18 | + current_size + current_size |
| 19 | + } else { |
| 20 | + current_size |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/// Stream errors reported by the bzip2 engine. Exception mapping belongs to |
| 25 | +/// the interpreter adapter. |
| 26 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 27 | +pub enum Bz2Error { |
| 28 | + /// `BZ_PARAM_ERROR` |
| 29 | + Param, |
| 30 | + /// `BZ_DATA_ERROR` / `BZ_DATA_ERROR_MAGIC` |
| 31 | + Data, |
| 32 | + /// `BZ_SEQUENCE_ERROR` |
| 33 | + Sequence, |
| 34 | + /// `BZ_MEM_ERROR` |
| 35 | + Mem, |
| 36 | +} |
| 37 | + |
| 38 | +impl From<Error> for Bz2Error { |
| 39 | + fn from(error: Error) -> Self { |
| 40 | + match error { |
| 41 | + Error::Param => Self::Param, |
| 42 | + Error::Data | Error::DataMagic => Self::Data, |
| 43 | + Error::Sequence => Self::Sequence, |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/// Incremental compressor. After `flush`, the stream is finished and must |
| 49 | +/// not be used again. |
| 50 | +pub struct Compressor { |
| 51 | + compress: Compress, |
| 52 | + flushed: bool, |
| 53 | +} |
| 54 | + |
| 55 | +impl Compressor { |
| 56 | + /// Create a compressor. Returns `None` when `compresslevel` is outside |
| 57 | + /// `1..=9`. A zero work factor selects libbz2's default of 30. |
| 58 | + pub fn new(compresslevel: i64) -> Option<Self> { |
| 59 | + let level = u32::try_from(compresslevel) |
| 60 | + .ok() |
| 61 | + .and_then(Compression::try_new)?; |
| 62 | + Some(Self { |
| 63 | + compress: Compress::new(level, 0), |
| 64 | + flushed: false, |
| 65 | + }) |
| 66 | + } |
| 67 | + |
| 68 | + #[must_use] |
| 69 | + pub fn is_flushed(&self) -> bool { |
| 70 | + self.flushed |
| 71 | + } |
| 72 | + |
| 73 | + /// Compress `data` without finishing the stream. |
| 74 | + pub fn compress(&mut self, data: &[u8]) -> Result<Vec<u8>, Bz2Error> { |
| 75 | + self.run(data, Action::Run) |
| 76 | + } |
| 77 | + |
| 78 | + /// Finish the stream. The compressor must not be used again. |
| 79 | + pub fn flush(&mut self) -> Result<Vec<u8>, Bz2Error> { |
| 80 | + self.flushed = true; |
| 81 | + self.run(&[], Action::Finish) |
| 82 | + } |
| 83 | + |
| 84 | + /// One pass over the input with the requested action, growing the output |
| 85 | + /// block whenever libbz2 fills it. |
| 86 | + fn run(&mut self, mut input: &[u8], action: Action) -> Result<Vec<u8>, Bz2Error> { |
| 87 | + let mut out = Vec::new(); |
| 88 | + let mut block = vec![0u8; INITIAL_BUFFER_SIZE]; |
| 89 | + loop { |
| 90 | + // In regular compression mode, stop when input data is exhausted. |
| 91 | + if action == Action::Run && input.is_empty() { |
| 92 | + break; |
| 93 | + } |
| 94 | + let previous_in = self.compress.total_in(); |
| 95 | + let previous_out = self.compress.total_out(); |
| 96 | + let status = self.compress.compress(input, &mut block, action)?; |
| 97 | + let consumed = (self.compress.total_in() - previous_in) as usize; |
| 98 | + let produced = (self.compress.total_out() - previous_out) as usize; |
| 99 | + out.extend_from_slice(&block[..produced]); |
| 100 | + input = &input[consumed..]; |
| 101 | + // In flushing mode, stop when all buffered data has been flushed. |
| 102 | + if action == Action::Finish && status == Status::StreamEnd { |
| 103 | + break; |
| 104 | + } |
| 105 | + if produced == block.len() { |
| 106 | + block = vec![0u8; new_buffer_size(block.len())]; |
| 107 | + } |
| 108 | + } |
| 109 | + out.shrink_to_fit(); |
| 110 | + Ok(out) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +/// Incremental decompressor. The first failure is latched so later calls |
| 115 | +/// can be refused by the caller; re-entering the native stream after a |
| 116 | +/// failure can write out of bounds. |
| 117 | +pub struct Decompressor { |
| 118 | + decompress: Decompress, |
| 119 | + eof: bool, |
| 120 | + failed: bool, |
| 121 | + needs_input: bool, |
| 122 | + unused_data: Vec<u8>, |
| 123 | + /// Input handed to `decompress` that libbz2 has not consumed yet. |
| 124 | + input_buffer: Vec<u8>, |
| 125 | +} |
| 126 | + |
| 127 | +impl Decompressor { |
| 128 | + /// Create a decompressor using the fast (non-`small`) algorithm. |
| 129 | + #[must_use] |
| 130 | + pub fn new() -> Self { |
| 131 | + Self { |
| 132 | + decompress: Decompress::new(false), |
| 133 | + eof: false, |
| 134 | + failed: false, |
| 135 | + needs_input: true, |
| 136 | + unused_data: Vec::new(), |
| 137 | + input_buffer: Vec::new(), |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + #[must_use] |
| 142 | + pub fn eof(&self) -> bool { |
| 143 | + self.eof |
| 144 | + } |
| 145 | + |
| 146 | + #[must_use] |
| 147 | + pub fn failed(&self) -> bool { |
| 148 | + self.failed |
| 149 | + } |
| 150 | + |
| 151 | + #[must_use] |
| 152 | + pub fn needs_input(&self) -> bool { |
| 153 | + self.needs_input |
| 154 | + } |
| 155 | + |
| 156 | + #[must_use] |
| 157 | + pub fn unused_data(&self) -> &[u8] { |
| 158 | + &self.unused_data |
| 159 | + } |
| 160 | + |
| 161 | + /// Decompress from new input and any bytes buffered by an earlier call. |
| 162 | + /// `max_length` of `None` means unlimited output. |
| 163 | + pub fn decompress( |
| 164 | + &mut self, |
| 165 | + data: &[u8], |
| 166 | + max_length: Option<usize>, |
| 167 | + ) -> Result<Vec<u8>, Bz2Error> { |
| 168 | + let max_length = max_length.unwrap_or(usize::MAX); |
| 169 | + let mut out = Vec::new(); |
| 170 | + let mut block = vec![0u8; INITIAL_BUFFER_SIZE.min(max_length)]; |
| 171 | + |
| 172 | + let mut failed = None; |
| 173 | + let mut stream_end = false; |
| 174 | + let leftover = { |
| 175 | + let mut chunks = Chunker::chain(&self.input_buffer, data); |
| 176 | + loop { |
| 177 | + let chunk = chunks.chunk(); |
| 178 | + let previous_in = self.decompress.total_in(); |
| 179 | + let previous_out = self.decompress.total_out(); |
| 180 | + let status = self.decompress.decompress(chunk, &mut block); |
| 181 | + let consumed = (self.decompress.total_in() - previous_in) as usize; |
| 182 | + let produced = (self.decompress.total_out() - previous_out) as usize; |
| 183 | + chunks.advance(consumed); |
| 184 | + out.extend_from_slice(&block[..produced]); |
| 185 | + match status { |
| 186 | + Err(error) => { |
| 187 | + failed = Some(error.into()); |
| 188 | + break; |
| 189 | + } |
| 190 | + Ok(Status::MemNeeded) => { |
| 191 | + failed = Some(Bz2Error::Mem); |
| 192 | + break; |
| 193 | + } |
| 194 | + Ok(Status::StreamEnd) => { |
| 195 | + stream_end = true; |
| 196 | + break; |
| 197 | + } |
| 198 | + Ok(_) => {} |
| 199 | + } |
| 200 | + if chunks.is_empty() { |
| 201 | + break; |
| 202 | + } |
| 203 | + if produced == block.len() { |
| 204 | + // The output block is full: grow it unless `max_length` |
| 205 | + // has already been reached. |
| 206 | + if out.len() == max_length { |
| 207 | + break; |
| 208 | + } |
| 209 | + block = vec![0u8; new_buffer_size(block.len()).min(max_length - out.len())]; |
| 210 | + } |
| 211 | + } |
| 212 | + if chunks.is_empty() { |
| 213 | + None |
| 214 | + } else { |
| 215 | + Some(chunks.to_vec()) |
| 216 | + } |
| 217 | + }; |
| 218 | + |
| 219 | + if let Some(error) = failed { |
| 220 | + return Err(self.fail(error)); |
| 221 | + } |
| 222 | + |
| 223 | + if stream_end { |
| 224 | + self.eof = true; |
| 225 | + self.needs_input = false; |
| 226 | + self.input_buffer.clear(); |
| 227 | + if let Some(unused) = leftover { |
| 228 | + self.unused_data = unused; |
| 229 | + } |
| 230 | + } else if let Some(remaining) = leftover { |
| 231 | + self.needs_input = false; |
| 232 | + self.input_buffer = remaining; |
| 233 | + } else { |
| 234 | + self.needs_input = true; |
| 235 | + self.input_buffer.clear(); |
| 236 | + } |
| 237 | + out.shrink_to_fit(); |
| 238 | + Ok(out) |
| 239 | + } |
| 240 | + |
| 241 | + /// Latch the first failure and drop the pending input with it. |
| 242 | + fn fail(&mut self, error: Bz2Error) -> Bz2Error { |
| 243 | + self.failed = true; |
| 244 | + self.needs_input = false; |
| 245 | + self.input_buffer = Vec::new(); |
| 246 | + error |
| 247 | + } |
| 248 | +} |
| 249 | + |
| 250 | +impl Default for Decompressor { |
| 251 | + fn default() -> Self { |
| 252 | + Self::new() |
| 253 | + } |
| 254 | +} |
| 255 | + |
| 256 | +#[cfg(test)] |
| 257 | +mod tests { |
| 258 | + use super::*; |
| 259 | + |
| 260 | + fn roundtrip(data: &[u8], level: i64) -> Vec<u8> { |
| 261 | + let mut compressor = Compressor::new(level).unwrap(); |
| 262 | + let mut encoded = compressor.compress(data).unwrap(); |
| 263 | + encoded.extend(compressor.flush().unwrap()); |
| 264 | + let mut decompressor = Decompressor::new(); |
| 265 | + let out = decompressor.decompress(&encoded, None).unwrap(); |
| 266 | + assert!(decompressor.eof()); |
| 267 | + out |
| 268 | + } |
| 269 | + |
| 270 | + #[test] |
| 271 | + fn invalid_level_is_rejected() { |
| 272 | + assert!(Compressor::new(0).is_none()); |
| 273 | + assert!(Compressor::new(10).is_none()); |
| 274 | + assert!(Compressor::new(-1).is_none()); |
| 275 | + } |
| 276 | + |
| 277 | + #[test] |
| 278 | + fn streaming_roundtrip() { |
| 279 | + let data = b"the quick brown fox jumps over the lazy dog".repeat(50); |
| 280 | + assert_eq!(roundtrip(&data, 9), data); |
| 281 | + } |
| 282 | + |
| 283 | + #[test] |
| 284 | + fn unused_data_after_stream_end() { |
| 285 | + let mut compressor = Compressor::new(9).unwrap(); |
| 286 | + let mut encoded = compressor.compress(b"hello").unwrap(); |
| 287 | + encoded.extend(compressor.flush().unwrap()); |
| 288 | + encoded.extend_from_slice(b"trailing"); |
| 289 | + |
| 290 | + let mut decompressor = Decompressor::new(); |
| 291 | + let out = decompressor.decompress(&encoded, None).unwrap(); |
| 292 | + assert_eq!(out, b"hello"); |
| 293 | + assert!(decompressor.eof()); |
| 294 | + assert!(!decompressor.needs_input()); |
| 295 | + assert_eq!(decompressor.unused_data(), b"trailing"); |
| 296 | + } |
| 297 | + |
| 298 | + #[test] |
| 299 | + fn max_length_leaves_unconsumed_input() { |
| 300 | + let data = b"abcdefghij".repeat(20); |
| 301 | + let mut compressor = Compressor::new(9).unwrap(); |
| 302 | + let mut encoded = compressor.compress(&data).unwrap(); |
| 303 | + encoded.extend(compressor.flush().unwrap()); |
| 304 | + |
| 305 | + let mut decompressor = Decompressor::new(); |
| 306 | + let first = decompressor.decompress(&encoded, Some(5)).unwrap(); |
| 307 | + assert_eq!(first.len(), 5); |
| 308 | + assert!(!decompressor.eof()); |
| 309 | + assert!(!decompressor.needs_input()); |
| 310 | + let rest = decompressor.decompress(&[], None).unwrap(); |
| 311 | + assert_eq!([first, rest].concat(), data); |
| 312 | + assert!(decompressor.eof()); |
| 313 | + } |
| 314 | + |
| 315 | + #[test] |
| 316 | + fn bad_data_latches_failure() { |
| 317 | + let mut decompressor = Decompressor::new(); |
| 318 | + let err = decompressor.decompress(b"not a bz2 stream", None); |
| 319 | + assert_eq!(err, Err(Bz2Error::Data)); |
| 320 | + assert!(decompressor.failed()); |
| 321 | + assert!(!decompressor.needs_input()); |
| 322 | + assert!(!decompressor.eof()); |
| 323 | + } |
| 324 | +} |
0 commit comments