diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 03e44d6a..3ccde19d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -48,6 +48,7 @@ jobs: - run: cargo test --features zlib-ng --no-default-features if: matrix.build != 'mingw' - run: cargo test --features zlib-rs --no-default-features + - run: cargo test --features fdeflate --no-default-features - run: cargo test --features cloudflare_zlib --no-default-features if: matrix.build != 'mingw' - run: | diff --git a/Cargo.toml b/Cargo.toml index 5853d792..dbbb369e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,10 +25,12 @@ zlib-rs = { version = "0.6.7", optional = true, default-features = false, featur ## This implementation uses only safe Rust code and doesn't require a C compiler. ## It provides good performance for most use cases while being completely portable. miniz_oxide = { version = "0.9.0", optional = true, features = ["simd"] } +fdeflate = { git = "https://github.com/Shnatsel/fdeflate.git", branch = "flate2-api-changes", optional = true } crc32fast = { version = "1.2.0", default-features = false, optional = true } document-features = { version = "0.2", optional = true } [dev-dependencies] +miniz_oxide = "0.9.0" futures = { version = "0.3", default-features = false } rand = "0.9" quickcheck = { version = "1.0", default-features = false } @@ -61,6 +63,9 @@ zlib-rs = ["any_zlib", "dep:zlib-rs"] # zlib-rs uses its own crc32 implementatio ## Use the pure Rust `miniz_oxide` backend. miniz_oxide = ["any_impl", "dep:miniz_oxide", "dep:crc32fast"] +## Use the pure Rust `fdeflate` backend. +fdeflate = ["any_impl", "dep:fdeflate", "dep:crc32fast"] + ## Use the system's installed zlib library. ## This is useful when you need compatibility with other C code that uses zlib, ## or when you want to use the system-provided zlib for consistency. diff --git a/README.md b/README.md index 5ea3f5dc..2bedf43a 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,14 @@ implementation at the cost of some `unsafe`, you can use `zlib-rs`: flate2 = { version = "1.1.10", features = ["zlib-rs", "runtime_detection"], default-features = false } ``` +### fdeflate backend on this branch + +The `fdeflate` feature selects a safe Rust backend with bounded streaming +buffers. It currently requires `std` and Rust 1.88 or newer. Large initialized +decompression destinations can be decoded into directly; small or uninitialized +destinations use a reusable 96 KiB history/output buffer. Compression and +decompression continue across internal buffer boundaries within a single call. + ### C backends While zlib-rs is [the fastest overall](https://trifectatech.org/blog/zlib-rs-is-faster-than-c/), diff --git a/examples/corpus_bench.rs b/examples/corpus_bench.rs new file mode 100644 index 00000000..b5636f68 --- /dev/null +++ b/examples/corpus_bench.rs @@ -0,0 +1,76 @@ +//! Compression benchmark for source, executable bytes, and low-entropy input. +//! Pass a directory containing `rust-source.bin` and `rg-binary.bin` snapshots. +//! Run with `cargo run --release --no-default-features --features fdeflate +//! --example corpus_bench -- `. Output is CSV; allocations are reused. +#![forbid(unsafe_code)] +use flate2::{Compress, Compression, FlushCompress, Status}; +use std::{ + hint::black_box, + time::{Duration, Instant}, +}; +fn main() { + let folder = std::env::args().nth(1).unwrap(); + println!("pattern,input_bytes,level,seconds,compressed_bytes"); + for pattern in ["source", "binary", "low16", "skewed"] { + let input = match pattern { + "source" => std::fs::read(format!("{folder}/rust-source.bin")).unwrap(), + "binary" => std::fs::read(format!("{folder}/rg-binary.bin")).unwrap(), + _ => { + let mut r = 12345678u32; + (0..1048576) + .map(|_| { + r ^= r << 13; + r ^= r >> 17; + r ^= r << 5; + if pattern == "low16" { + (r % 16) as u8 + } else { + match r % 100 { + 0 => r as u8, + 1..=2 => (r % 32) as u8, + 11..=50 => (r % 16) as u8, + 51..=80 => (r % 8) as u8, + _ => 0, + } + } + }) + .collect() + } + }; + for level in [1, 4, 6, 9] { + let mut encoder = Compress::new(Compression::new(level), true); + let mut output = vec![0; 32768]; + let mut sizes = 0; + let mut operation = || { + encoder.reset(); + loop { + let status = encoder + .compress( + &input[encoder.total_in() as usize..], + &mut output, + FlushCompress::Finish, + ) + .unwrap(); + black_box(&output); + if status == Status::StreamEnd { + break; + } + } + sizes = encoder.total_out(); + }; + operation(); + let mut times = [0.; 5]; + for t in &mut times { + let start = Instant::now(); + let mut n = 0; + while start.elapsed() < Duration::from_millis(50) { + operation(); + n += 1; + } + *t = start.elapsed().as_secs_f64() / n as f64; + } + times.sort_by(f64::total_cmp); + println!("{pattern},{},{level},{:.9},{sizes}", input.len(), times[2]); + } + } +} diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 8defdd26..cf33db0d 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -12,6 +12,10 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" flate2 = { path = ".." } +miniz_oxide = "0.9.0" + +[features] +fdeflate = ["flate2/fdeflate"] # Prevent this from interfering with workspaces [workspace] @@ -22,3 +26,9 @@ name = "fuzz_gz_roundtrip" path = "fuzz_targets/fuzz_gz_roundtrip.rs" test = false doc = false + +[[bin]] +name = "streaming" +path = "fuzz_targets/streaming.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/streaming.rs b/fuzz/fuzz_targets/streaming.rs new file mode 100644 index 00000000..ac142ae4 --- /dev/null +++ b/fuzz/fuzz_targets/streaming.rs @@ -0,0 +1,4 @@ +#![no_main] +#[path = "../streaming.rs"] +mod streaming; +libfuzzer_sys::fuzz_target!(|data: &[u8]| streaming::exercise(data)); diff --git a/fuzz/streaming.rs b/fuzz/streaming.rs new file mode 100644 index 00000000..2e221d07 --- /dev/null +++ b/fuzz/streaming.rs @@ -0,0 +1,152 @@ +//! Shared by deterministic regression tests and the differential fuzz target. +#![forbid(unsafe_code)] +use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; + +pub fn exercise(data: &[u8]) { + if data.len() < 8 { + return; + } + let zlib = data[0] & 1 != 0; + let level = data[1] % 10; + let input = &data[8..]; + let mut compressor = Compress::new(Compression::new(level.into()), zlib); + // Reset with both pending output and uncommitted parser work. + compressor + .compress(input, &mut [0; 7], FlushCompress::None) + .unwrap(); + compressor.reset(); + let mut encoded = Vec::new(); + let mut output = vec![0; 32768]; + let chunk_size = 1 + u16::from_le_bytes([data[2], data[3]]) as usize; + let flush = match data[4] % 4 { + 0 => FlushCompress::None, + 1 => FlushCompress::Partial, + 2 => FlushCompress::Sync, + _ => FlushCompress::Full, + }; + let out_size = 7 + u16::from_le_bytes([data[5], data[6]]) as usize % (output.len() - 7); + let mut end = chunk_size.min(input.len()); + for iteration in 0..(input.len() + 100) * 10 { + let before = (compressor.total_in(), compressor.total_out()); + let finishing = end == input.len(); + let mode = if finishing { + FlushCompress::Finish + } else { + flush + }; + // Zero-sized calls must neither lose input nor hang. + let space = if iteration % 7 == 0 { 0 } else { out_size }; + let status = compressor + .compress(&input[before.0 as usize..end], &mut output[..space], mode) + .unwrap(); + let produced = (compressor.total_out() - before.1) as usize; + assert!(produced <= space); + assert!(compressor.total_in() as usize <= end); + encoded.extend_from_slice(&output[..produced]); + if status == Status::StreamEnd { + break; + } + if !finishing && compressor.total_in() as usize == end && space > 0 && produced < space { + end = (end + chunk_size).min(input.len()); + } + if iteration + 1 == (input.len() + 100) * 10 { + panic!("compression did not finish"); + } + } + assert_eq!(compressor.total_in() as usize, input.len()); + let independent = if zlib { + miniz_oxide::inflate::decompress_to_vec_zlib(&encoded) + } else { + miniz_oxide::inflate::decompress_to_vec(&encoded) + } + .unwrap_or_else(|_| { + panic!( + "invalid encoding: controls={:?}, input_len={}, encoded={:?}", + &data[..8], + input.len(), + &encoded[..encoded.len().min(100)] + ) + }); + assert_eq!(independent, input); + decode(&encoded, zlib, data, Some(input)); + // Corruption and truncation retain bounded progress. On successful decoding, + // compare the result with an independent implementation. + let mut malformed = encoded; + if !malformed.is_empty() { + let index = usize::from(data[7]) % malformed.len(); + malformed[index] ^= data[4]; + if data[0] & 2 != 0 { + malformed.truncate(index); + } + } + decode(&malformed, zlib, data, None); + decode(input, zlib, data, None); +} + +fn decode(encoded: &[u8], zlib: bool, controls: &[u8], expected: Option<&[u8]>) { + let mut decoder = Decompress::new(zlib); + let mut decoded = Vec::new(); + let mut output = [0; 8192]; + decoder + .decompress(&[0xff; 10], &mut output, FlushDecompress::None) + .ok(); + decoder.reset(zlib); + let input_chunk = 1 + usize::from(controls[2]); + let output_chunk = 1 + usize::from(controls[3]) * 31; + let mut ended = false; + for iteration in 0..(encoded.len() + 100) * 100 { + let before = (decoder.total_in() as usize, decoder.total_out() as usize); + let end = (before.0 + input_chunk).min(encoded.len()); + let space = if iteration % 11 == 0 { 0 } else { output_chunk }; + let result = decoder.decompress( + &encoded[before.0..end], + &mut output[..space], + FlushDecompress::None, + ); + let produced = decoder.total_out() as usize - before.1; + assert!(produced <= space); + assert!(decoder.total_in() as usize <= end); + decoded.extend_from_slice(&output[..produced]); + if matches!(result, Ok(Status::StreamEnd)) { + ended = true; + break; + } + if result.is_err() { + break; + } + if space != 0 && before == (decoder.total_in() as usize, decoder.total_out() as usize) { + assert!(expected.is_none(), "valid stream stalled"); + break; + } + // Do not let malformed streams turn a fuzz iteration into a zip bomb. + if decoded.len() > 8 * 1024 * 1024 { + return; + } + } + if let Some(expected) = expected { + assert!(ended); + assert_eq!(decoded, expected); + assert_eq!(decoder.total_in() as usize, encoded.len()); + } else if ended { + let mut independent = vec![0; decoded.len() + 1]; + let mut state = miniz_oxide::inflate::stream::InflateState::new_boxed(if zlib { + miniz_oxide::DataFormat::Zlib + } else { + miniz_oxide::DataFormat::Raw + }); + let result = miniz_oxide::inflate::stream::inflate( + &mut state, + encoded, + &mut independent, + miniz_oxide::MZFlush::Finish, + ); + assert_eq!( + result.status, + Ok(miniz_oxide::MZStatus::StreamEnd), + "zlib={zlib}, encoded={encoded:?}, decoded_len={}", + decoded.len() + ); + assert_eq!(result.bytes_written, decoded.len()); + assert_eq!(&independent[..decoded.len()], decoded); + } +} diff --git a/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs new file mode 100644 index 00000000..59460a51 --- /dev/null +++ b/src/ffi/fdeflate.rs @@ -0,0 +1,367 @@ +//! Implementation for the `fdeflate` Rust backend. +#![forbid(unsafe_code)] + +use super::*; +use crate::mem::{compress_failed, decompress_failed}; +use ::fdeflate::{ + CompressionFlush, CompressionProgress, CompressionStatus, DecompressionError as FdeflateError, + DecompressionStatus, +}; +use alloc::vec::Vec; +use core::{fmt, mem::MaybeUninit}; + +pub const MZ_NO_FLUSH: isize = 0; +pub const MZ_PARTIAL_FLUSH: isize = 1; +pub const MZ_SYNC_FLUSH: isize = 2; +pub const MZ_FULL_FLUSH: isize = 3; +pub const MZ_FINISH: isize = 4; +pub const MZ_DEFAULT_WINDOW_BITS: core::ffi::c_int = 15; + +const HISTORY: usize = 32 * 1024; +const TAIL: usize = 64 * 1024; +const SCRATCH: usize = HISTORY + TAIL; + +#[derive(Clone, Default)] +pub struct ErrorMessage(Option<&'static str>); +impl ErrorMessage { + pub fn get(&self) -> Option<&str> { + self.0 + } +} + +fn format_from_bool(zlib_header: bool) -> ::fdeflate::Format { + if zlib_header { + ::fdeflate::Format::Zlib + } else { + ::fdeflate::Format::Raw + } +} + +fn decompression_message(error: FdeflateError) -> &'static str { + match error { + FdeflateError::BadZlibHeader => "bad zlib header", + FdeflateError::InsufficientInput => "insufficient input", + FdeflateError::InvalidBlockType => "invalid block type", + FdeflateError::InvalidUncompressedBlockLength => "invalid uncompressed block length", + FdeflateError::InvalidHlit => "invalid literal/length code count", + FdeflateError::InvalidHdist => "invalid distance code count", + FdeflateError::InvalidCodeLengthRepeat => "invalid code length repeat", + FdeflateError::BadCodeLengthHuffmanTree => "bad code length huffman tree", + FdeflateError::BadLiteralLengthHuffmanTree => "bad literal/length huffman tree", + FdeflateError::BadDistanceHuffmanTree => "bad distance huffman tree", + FdeflateError::InvalidLiteralLengthCode => "invalid literal/length code", + FdeflateError::InvalidDistanceCode => "invalid distance code", + FdeflateError::InputStartsWithRun => "input starts with a run", + FdeflateError::DistanceTooFarBack => "distance too far back", + FdeflateError::WrongChecksum => "wrong checksum", + FdeflateError::ExtraInput => "extra input", + } +} + +fn compression_flush(flush: FlushCompress) -> CompressionFlush { + match flush { + FlushCompress::None => CompressionFlush::None, + FlushCompress::Partial => CompressionFlush::Partial, + FlushCompress::Sync => CompressionFlush::Sync, + FlushCompress::Full => CompressionFlush::Full, + FlushCompress::Finish => CompressionFlush::Finish, + } +} + +pub struct Deflate { + inner: ::fdeflate::StreamingCompressor, + zlib_header: bool, + total_in: u64, + total_out: u64, +} +impl fmt::Debug for Deflate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("fdeflate::Deflate") + .field("total_in", &self.total_in) + .field("total_out", &self.total_out) + .finish() + } +} +impl Deflate { + fn account(&mut self, progress: CompressionProgress) -> Result { + self.total_in += progress.consumed as u64; + self.total_out += progress.produced as u64; + match progress.status { + Err(_) => compress_failed(ErrorMessage(Some( + "input supplied after finishing compression", + ))), + Ok(CompressionStatus::StreamEnd) => Ok(Status::StreamEnd), + Ok(_) if progress.consumed == 0 && progress.produced == 0 => Ok(Status::BufError), + Ok(_) => Ok(Status::Ok), + } + } +} +impl DeflateBackend for Deflate { + fn make(level: Compression, zlib_header: bool, _window_bits: u8) -> Self { + Self { + inner: ::fdeflate::StreamingCompressor::new(level.level().min(9) as u8, zlib_header), + zlib_header, + total_in: 0, + total_out: 0, + } + } + fn compress( + &mut self, + input: &[u8], + output: &mut [u8], + flush: FlushCompress, + ) -> Result { + let progress = self.inner.process(input, output, compression_flush(flush)); + self.account(progress) + } + fn compress_uninit( + &mut self, + input: &[u8], + output: &mut [MaybeUninit], + flush: FlushCompress, + ) -> Result { + let progress = self + .inner + .process_uninit(input, output, compression_flush(flush)); + self.account(progress) + } + fn reset(&mut self) { + self.inner.reset(self.zlib_header); + self.total_in = 0; + self.total_out = 0; + } +} +impl Backend for Deflate { + fn total_in(&self) -> u64 { + self.total_in + } + fn total_out(&self) -> u64 { + self.total_out + } +} + +trait Output { + fn len(&self) -> usize; + fn put(&mut self, offset: usize, bytes: &[u8]); + fn initialized(&mut self) -> Option<&mut [u8]> { + None + } +} +impl Output for [u8] { + fn len(&self) -> usize { + self.len() + } + fn put(&mut self, offset: usize, bytes: &[u8]) { + self[offset..offset + bytes.len()].copy_from_slice(bytes); + } + fn initialized(&mut self) -> Option<&mut [u8]> { + Some(self) + } +} +impl Output for [MaybeUninit] { + fn len(&self) -> usize { + self.len() + } + fn put(&mut self, offset: usize, bytes: &[u8]) { + // .write_copy_of_slice() has MSRV of 1.93, we can't use it yet + for (destination, &byte) in self[offset..offset + bytes.len()].iter_mut().zip(bytes) { + destination.write(byte); + } + } +} + +pub struct Inflate { + inner: ::fdeflate::Decompressor, + scratch: Vec, + drain_pos: usize, + decode_pos: usize, + total_in: u64, + total_out: u64, + done: bool, + error: Option<&'static str>, +} +impl fmt::Debug for Inflate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("fdeflate::Inflate") + .field("drain_pos", &self.drain_pos) + .field("decode_pos", &self.decode_pos) + .field("total_in", &self.total_in) + .field("total_out", &self.total_out) + .field("done", &self.done) + .field("error", &self.error) + .finish() + } +} +impl Inflate { + fn drain(&mut self, output: &mut O, offset: &mut usize) { + let n = (self.decode_pos - self.drain_pos).min(output.len() - *offset); + if n != 0 { + output.put(*offset, &self.scratch[self.drain_pos..self.drain_pos + n]); + } + self.drain_pos += n; + *offset += n; + self.total_out += n as u64; + } + + fn prepare_scratch(&mut self, writable: usize) { + if self.scratch.is_empty() { + self.scratch.resize(SCRATCH, 0); + } + if self.decode_pos + writable > SCRATCH { + let keep = self.decode_pos.min(HISTORY); + self.scratch + .copy_within(self.decode_pos - keep..self.decode_pos, 0); + self.decode_pos = keep; + self.drain_pos = keep; + } + } + + fn run( + &mut self, + input: &[u8], + output: &mut O, + flush: FlushDecompress, + ) -> Result { + if let Some(error) = self.error { + return decompress_failed(ErrorMessage(Some(error))); + } + let before = (self.total_in, self.total_out); + let mut input_pos = 0; + let mut output_pos = 0; + loop { + self.drain(output, &mut output_pos); + if self.drain_pos != self.decode_pos || self.done { + break; + } + + // The current call's output can replace scratch history once it + // contains a whole window. A fresh stream needs no history at all. + if (self.decode_pos == 0 || output_pos >= HISTORY) && output.len() - output_pos >= TAIL + { + if let Some(destination) = output.initialized() { + let progress = + self.inner + .read_progress(&input[input_pos..], destination, output_pos); + input_pos += progress.consumed; + self.total_in += progress.consumed as u64; + output_pos += progress.produced; + self.total_out += progress.produced as u64; + match progress.status { + Err(error) => { + let message = decompression_message(error); + self.error = Some(message); + return decompress_failed(ErrorMessage(Some(message))); + } + Ok(status) => { + self.done = status == DecompressionStatus::Done; + if !self.done { + let keep = output_pos.min(HISTORY); + self.prepare_scratch(0); + self.scratch[..keep] + .copy_from_slice(&destination[output_pos - keep..output_pos]); + self.decode_pos = keep; + self.drain_pos = keep; + } + if self.done || status == DecompressionStatus::NeedsInput { + break; + } + // A full destination may still admit non-producing + // headers/trailers through the scratch path below. + continue; + } + } + } + } + + let remaining = output.len() - output_pos; + let writable = if remaining == 0 { + 0 + } else if output.len() >= SCRATCH && output_pos < HISTORY { + // Establish history in a large destination, then decode into it. + HISTORY - output_pos + } else { + TAIL + }; + self.prepare_scratch(writable); + let progress = self.inner.read_progress( + &input[input_pos..], + &mut self.scratch[..self.decode_pos + writable], + self.decode_pos, + ); + input_pos += progress.consumed; + self.total_in += progress.consumed as u64; + self.decode_pos += progress.produced; + self.drain(output, &mut output_pos); + match progress.status { + Err(error) => { + let message = decompression_message(error); + self.error = Some(message); + return decompress_failed(ErrorMessage(Some(message))); + } + Ok(status) => { + self.done = status == DecompressionStatus::Done; + if self.done + || status == DecompressionStatus::NeedsInput + || (progress.consumed == 0 && progress.produced == 0) + { + break; + } + } + } + } + if self.done && self.drain_pos == self.decode_pos { + Ok(Status::StreamEnd) + } else if flush == FlushDecompress::Finish || before == (self.total_in, self.total_out) { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + } + } +} +impl InflateBackend for Inflate { + fn make(zlib_header: bool, _window_bits: u8) -> Self { + Self { + inner: ::fdeflate::Decompressor::new_with_format(format_from_bool(zlib_header)), + scratch: Vec::new(), + drain_pos: 0, + decode_pos: 0, + total_in: 0, + total_out: 0, + done: false, + error: None, + } + } + fn decompress( + &mut self, + input: &[u8], + output: &mut [u8], + flush: FlushDecompress, + ) -> Result { + self.run(input, output, flush) + } + fn decompress_uninit( + &mut self, + input: &[u8], + output: &mut [MaybeUninit], + flush: FlushDecompress, + ) -> Result { + self.run(input, output, flush) + } + fn reset(&mut self, zlib_header: bool) { + self.inner.reset(format_from_bool(zlib_header)); + self.drain_pos = 0; + self.decode_pos = 0; + self.total_in = 0; + self.total_out = 0; + self.done = false; + self.error = None; + } +} +impl Backend for Inflate { + fn total_in(&self) -> u64 { + self.total_in + } + fn total_out(&self) -> u64 { + self.total_out + } +} diff --git a/src/ffi/mod.rs b/src/ffi/mod.rs index 111ab4ef..025e22c1 100644 --- a/src/ffi/mod.rs +++ b/src/ffi/mod.rs @@ -71,10 +71,24 @@ mod zlib_rs; #[cfg(all(not(feature = "any_c_zlib"), feature = "zlib-rs"))] pub use self::zlib_rs::*; +// Use fdeflate when no fully compliant zlib is selected and fdeflate is explicitly requested. +#[cfg(all(not(feature = "any_zlib"), feature = "fdeflate"))] +mod fdeflate; +#[cfg(all(not(feature = "any_zlib"), feature = "fdeflate"))] +pub use self::fdeflate::*; + // Use miniz_oxide when no fully compliant zlib is selected. -#[cfg(all(not(feature = "any_zlib"), feature = "miniz_oxide"))] +#[cfg(all( + not(feature = "any_zlib"), + not(feature = "fdeflate"), + feature = "miniz_oxide" +))] mod miniz_oxide; -#[cfg(all(not(feature = "any_zlib"), feature = "miniz_oxide"))] +#[cfg(all( + not(feature = "any_zlib"), + not(feature = "fdeflate"), + feature = "miniz_oxide" +))] pub use self::miniz_oxide::*; // If no backend is enabled, fail fast with a clear error message. diff --git a/src/mem.rs b/src/mem.rs index d0c53335..278cb37f 100644 --- a/src/mem.rs +++ b/src/mem.rs @@ -115,7 +115,10 @@ pub enum FlushDecompress { /// The inner state for an error when decompressing #[derive(Clone, Debug)] pub(crate) enum DecompressErrorInner { - General { msg: ErrorMessage }, + General { + msg: ErrorMessage, + }, + #[allow(dead_code)] NeedsDictionary(u32), } @@ -143,6 +146,7 @@ pub(crate) fn decompress_failed(msg: ErrorMessage) -> Result(adler: u32) -> Result { Err(DecompressError(DecompressErrorInner::NeedsDictionary( adler, diff --git a/src/zio.rs b/src/zio.rs index 4f18d721..78906b88 100644 --- a/src/zio.rs +++ b/src/zio.rs @@ -12,6 +12,7 @@ pub struct Writer { obj: Option, pub data: D, buf: Vec, + buf_pos: usize, finished: bool, } @@ -190,6 +191,7 @@ impl Writer { obj: Some(w), data: d, buf: Vec::with_capacity(32 * 1024), + buf_pos: 0, finished: false, } } @@ -235,6 +237,7 @@ impl Writer { pub fn replace(&mut self, w: W) -> W { self.buf.clear(); + self.buf_pos = 0; self.finished = false; mem::replace(self.get_mut(), w) } @@ -294,15 +297,18 @@ impl Writer { } fn dump(&mut self) -> io::Result<()> { - // TODO: should manage this buffer not with `drain` but probably more of - // a deque-like strategy. - while !self.buf.is_empty() { - let n = self.obj.as_mut().unwrap().write(&self.buf)?; + while self.buf_pos < self.buf.len() { + let n = match self.obj.as_mut().unwrap().write(&self.buf[self.buf_pos..]) { + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + result => result?, + }; if n == 0 { return Err(io::ErrorKind::WriteZero.into()); } - self.buf.drain(..n); + self.buf_pos += n; } + self.buf.clear(); + self.buf_pos = 0; Ok(()) } } @@ -313,22 +319,35 @@ impl Write for Writer { } fn flush(&mut self) -> io::Result<()> { - self.data - .run_vec(&[], &mut self.buf, Flush::sync()) - .map_err(Into::into)?; - - // Unfortunately miniz doesn't actually tell us when we're done with - // pulling out all the data from the internal stream. To remedy this we - // have to continually ask the stream for more memory until it doesn't - // give us a chunk of memory the same size as our own internal buffer, - // at which point we assume it's reached the end. + // Drain previously encoded output before requesting Sync. In particular, + // miniz can return a short buffer after draining old output without + // processing the new flush request. Once that output is drained, a Sync + // call with spare output capacity completes the flush. loop { - self.dump()?; - let before = self.data.total_out(); - self.data - .run_vec(&[], &mut self.buf, Flush::none()) + loop { + self.dump()?; + let status = self + .data + .run_vec(&[], &mut self.buf, Flush::none()) + .map_err(Into::into)?; + self.finished |= status == Status::StreamEnd; + if self.buf.is_empty() { + break; + } + } + if self.finished { + break; + } + let status = self + .data + .run_vec(&[], &mut self.buf, Flush::sync()) .map_err(Into::into)?; - if before == self.data.total_out() { + if status == Status::StreamEnd { + self.finished = true; + } + let complete = self.buf.len() < self.buf.capacity() || self.finished; + self.dump()?; + if complete { break; } } diff --git a/tests/fdeflate.rs b/tests/fdeflate.rs new file mode 100644 index 00000000..9b44dbaa --- /dev/null +++ b/tests/fdeflate.rs @@ -0,0 +1,198 @@ +#![cfg(all(feature = "fdeflate", not(feature = "any_zlib")))] + +use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; +use std::io::{Read, Write}; + +fn compress_raw(input: &[u8]) -> Vec { + let mut encoded = Vec::with_capacity(input.len() + 1024); + let mut encoder = Compress::new(Compression::default(), false); + let status = encoder + .compress_vec(input, &mut encoded, FlushCompress::Finish) + .unwrap(); + assert_eq!(status, Status::StreamEnd); + encoded +} + +fn decompress_raw(encoded: &[u8], expected_len: usize) -> Vec { + let mut decoder = Decompress::new(false); + let mut decoded = vec![0; expected_len]; + let status = decoder + .decompress(encoded, &mut decoded, FlushDecompress::Finish) + .unwrap(); + assert_eq!(status, Status::StreamEnd); + decoded.truncate(decoder.total_out() as usize); + decoded +} + +#[test] +fn raw_roundtrip_with_one_byte_output() { + let input = vec![b'a'; 128 * 1024]; + let encoded = compress_raw(&input); + let mut decoder = Decompress::new(false); + let mut decoded = Vec::with_capacity(input.len()); + let mut input_pos = 0; + + loop { + let before_in = decoder.total_in(); + let before_out = decoder.total_out(); + let mut byte = [0; 1]; + let status = decoder + .decompress(&encoded[input_pos..], &mut byte, FlushDecompress::None) + .unwrap(); + input_pos += (decoder.total_in() - before_in) as usize; + let written = (decoder.total_out() - before_out) as usize; + decoded.extend_from_slice(&byte[..written]); + + if status == Status::StreamEnd { + break; + } + + assert!( + written != 0 || decoder.total_in() != before_in, + "decoder made no progress" + ); + } + + assert_eq!(decoded, input); + assert_eq!(input_pos, encoded.len()); +} + +#[test] +fn raw_trailing_bytes_remain_unconsumed() { + let input = b"raw stream with extra data after it"; + let encoded = compress_raw(input); + let mut with_trailing = encoded.clone(); + with_trailing.extend_from_slice(b"extra"); + + let mut decoder = Decompress::new(false); + let mut decoded = vec![0; 1024]; + let status = decoder + .decompress(&with_trailing, &mut decoded, FlushDecompress::Finish) + .unwrap(); + + assert_eq!(status, Status::StreamEnd); + assert_eq!(decoder.total_in(), encoded.len() as u64); + assert_eq!(&decoded[..decoder.total_out() as usize], input); +} + +#[test] +fn large_no_flush_call_preserves_streaming_backpressure() { + // One token can cover 258 bytes, so a bounded token buffer can accept + // several MiB of repetitive input before producing a block. + let input = vec![0x5a; 8 * 1024 * 1024]; + let mut output = [0; 1]; + let mut encoder = Compress::new(Compression::default(), false); + + let status = encoder + .compress(&input, &mut output, FlushCompress::None) + .unwrap(); + + assert_eq!(status, Status::Ok); + assert!( + encoder.total_in() > 0, + "the compressor should still accept some input" + ); + assert!( + encoder.total_in() < input.len() as u64, + "fdeflate should return to the caller before buffering the whole input" + ); +} + +#[test] +fn zlib_trailing_bytes_remain_unconsumed() { + let input = b"zlib stream with extra data after it"; + let mut encoded = Vec::with_capacity(1024); + let mut encoder = Compress::new(Compression::default(), true); + assert_eq!( + encoder + .compress_vec(input, &mut encoded, FlushCompress::Finish) + .unwrap(), + Status::StreamEnd + ); + let compressed_len = encoded.len(); + encoded.extend_from_slice(b"extra"); + + let mut decoder = Decompress::new(true); + let mut decoded = vec![0; 1024]; + let status = decoder + .decompress(&encoded, &mut decoded, FlushDecompress::Finish) + .unwrap(); + + assert_eq!(status, Status::StreamEnd); + assert_eq!(decoder.total_in(), compressed_len as u64); + assert_eq!(&decoded[..decoder.total_out() as usize], input); +} + +#[test] +fn partial_sync_and_full_flush_roundtrip() { + for flush in [ + FlushCompress::Partial, + FlushCompress::Sync, + FlushCompress::Full, + ] { + let first = b"first half first half first half"; + let second = b"second half second half second half"; + let mut encoded = Vec::with_capacity(4096); + let mut encoder = Compress::new(Compression::default(), false); + encoder.compress_vec(first, &mut encoded, flush).unwrap(); + assert_eq!( + encoder + .compress_vec(second, &mut encoded, FlushCompress::Finish) + .unwrap(), + Status::StreamEnd + ); + + let mut expected = Vec::new(); + expected.extend_from_slice(first); + expected.extend_from_slice(second); + assert_eq!(decompress_raw(&encoded, expected.len()), expected); + } +} + +#[test] +fn read_and_write_wrappers_roundtrip_single_zero() { + let input = [0]; + let direct_encoded = compress_raw(&input); + assert_eq!(decompress_raw(&direct_encoded, input.len()), input); + + let mut encoder = flate2::read::DeflateEncoder::new(&input[..], Compression::default()); + let mut encoded = Vec::new(); + encoder.read_to_end(&mut encoded).unwrap(); + + let mut reader = flate2::read::DeflateDecoder::new(&encoded[..]); + let mut decoded = Vec::new(); + reader.read_to_end(&mut decoded).unwrap(); + assert_eq!(decoded, input); + + let mut writer = flate2::write::DeflateEncoder::new( + flate2::write::DeflateDecoder::new(Vec::new()), + Compression::default(), + ); + writer.write_all(&input).unwrap(); + assert_eq!(writer.finish().unwrap().finish().unwrap(), input); +} + +#[test] +fn checksum_error_accounts_for_output_and_is_sticky_until_reset() { + let input = vec![42; 200000]; + let mut encoded = ::fdeflate::compress_to_vec_with_level(&input, 6); + *encoded.last_mut().unwrap() ^= 1; + let mut decoder = Decompress::new(true); + let mut output = Vec::with_capacity(input.len()); + assert!(decoder + .decompress_vec(&encoded, &mut output, FlushDecompress::Finish) + .is_err()); + assert_eq!(output, input); + let counters = (decoder.total_in(), decoder.total_out()); + assert!(decoder + .decompress(&[], &mut [0; 20], FlushDecompress::None) + .is_err()); + assert_eq!(counters, (decoder.total_in(), decoder.total_out())); + decoder.reset(false); + assert_eq!( + decoder + .decompress(&[3, 0], &mut [], FlushDecompress::Finish) + .unwrap(), + Status::StreamEnd + ); +} diff --git a/tests/streaming-random.rs b/tests/streaming-random.rs new file mode 100644 index 00000000..15b80e43 --- /dev/null +++ b/tests/streaming-random.rs @@ -0,0 +1,34 @@ +// Malformed-input acceptance and resetting unfinished streams differ in other backends. +#![cfg(all(feature = "fdeflate", not(feature = "any_zlib")))] + +#[path = "../fuzz/streaming.rs"] +mod streaming; + +#[test] +fn deterministic_chunk_flush_reset_and_corruption_matrix() { + let mut state = 179u32; + for size in [0, 1, 258, 1023, 1024, 32768, 98304, 131072, 500000] { + for pattern in 0..4 { + for level in 0..10 { + let mut input: Vec<_> = (0..size + 8) + .map(|i| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + if i < 8 || pattern == 0 { + state as u8 + } else if pattern == 1 { + b'a' + } else if pattern == 2 { + (state % 32) as u8 + } else { + (i % 251) as u8 + } + }) + .collect(); + input[1] = level; + streaming::exercise(&input); + } + } + } +} diff --git a/tests/streaming.rs b/tests/streaming.rs new file mode 100644 index 00000000..695102c0 --- /dev/null +++ b/tests/streaming.rs @@ -0,0 +1,257 @@ +//! Contracts shared by all backends, including writer backpressure. +use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; +use std::io::{self, Write}; + +fn random(len: usize) -> Vec { + let mut state = 0x12345678u32; + (0..len) + .map(|_| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state as u8 + }) + .collect() +} + +fn encode(input: &[u8], zlib: bool) -> Vec { + let mut encoder = Compress::new(Compression::default(), zlib); + let mut output = Vec::with_capacity(input.len() * 2 + 1024); + assert_eq!( + encoder + .compress_vec(input, &mut output, FlushCompress::Finish) + .unwrap(), + Status::StreamEnd + ); + assert_eq!(encoder.total_in() as usize, input.len()); + output +} + +#[test] +fn empty_stream_and_separate_trailer_need_no_spare_output() { + for zlib in [false, true] { + let encoded = encode(b"", zlib); + let mut decoder = Decompress::new(zlib); + assert_eq!( + decoder + .decompress(&encoded, &mut [], FlushDecompress::Finish) + .unwrap(), + Status::StreamEnd + ); + assert_eq!(decoder.total_in() as usize, encoded.len()); + } + let encoded = encode(b"hello", true); + let split = encoded.len() - 4; + let mut decoder = Decompress::new(true); + let mut output = [0; 5]; + decoder + .decompress(&encoded[..split], &mut output, FlushDecompress::None) + .unwrap(); + assert_eq!(&output, b"hello"); + assert_eq!( + decoder + .decompress( + &encoded[decoder.total_in() as usize..], + &mut [], + FlushDecompress::Finish + ) + .unwrap(), + Status::StreamEnd + ); + assert_eq!(decoder.total_in() as usize, encoded.len()); +} + +#[test] +fn large_finish_and_vec_output_complete_in_one_call() { + let input = random(1024 * 1024); + for zlib in [false, true] { + let encoded = encode(&input, zlib); + let mut decoder = Decompress::new(zlib); + let mut output = vec![0; input.len()]; + assert_eq!( + decoder + .decompress(&encoded, &mut output, FlushDecompress::Finish) + .unwrap(), + Status::StreamEnd + ); + assert_eq!(output, input); + decoder.reset(zlib); + let mut output = Vec::with_capacity(input.len()); + assert_eq!( + decoder + .decompress_vec(&encoded, &mut output, FlushDecompress::Finish) + .unwrap(), + Status::StreamEnd + ); + assert_eq!(output, input); + } +} + +#[test] +fn decoding_chunk_schedules_preserve_history_and_trailing_bytes() { + for zlib in [false, true] { + for size in [1, 32768, 65536, 98305, 270000] { + let mut input = random(size); + for i in 32768..size { + input[i] = input[i - 32768]; + } + let mut encoded = encode(&input, zlib); + let end = encoded.len(); + encoded.extend_from_slice(b"trailing bytes"); + for (ic, oc) in [ + (1, 1), + (7, 1), + (1, 4096), + (7, 997), + (4096, 32768), + (4096, 131072), + (7, 131072), + (999999, 65536), + (999999, 999999), + ] { + let mut decoder = Decompress::new(zlib); + let mut output = vec![0; size]; + loop { + let (bi, bo) = (decoder.total_in() as usize, decoder.total_out() as usize); + let status = decoder + .decompress( + &encoded[bi..(bi + ic).min(encoded.len())], + &mut output[bo..(bo + oc).min(size)], + FlushDecompress::None, + ) + .unwrap(); + assert!(decoder.total_in() as usize <= end); + if status == Status::StreamEnd { + break; + } + assert_ne!( + (bi as u64, bo as u64), + (decoder.total_in(), decoder.total_out()), + "size={size} chunks={ic},{oc} zlib={zlib}" + ); + } + assert_eq!(decoder.total_in() as usize, end); + assert_eq!(output, input); + } + } + } +} + +#[test] +fn alternating_slice_and_vec_output_preserves_decoder_history() { + let mut input = random(500000); + for i in 32768..input.len() { + input[i] = input[i - 32768]; + } + for zlib in [false, true] { + let encoded = encode(&input, zlib); + let mut decoder = Decompress::new(zlib); + let mut decoded = Vec::new(); + let mut slice = vec![0; 131072]; + let mut spare = Vec::with_capacity(131072); + let mut step = 0; + loop { + let (bi, bo) = (decoder.total_in() as usize, decoder.total_out()); + let end = (bi + 4096).min(encoded.len()); + let status = if step % 2 == 0 { + let status = decoder + .decompress(&encoded[bi..end], &mut slice, FlushDecompress::None) + .unwrap(); + decoded.extend_from_slice(&slice[..(decoder.total_out() - bo) as usize]); + status + } else { + spare.clear(); + let status = decoder + .decompress_vec(&encoded[bi..end], &mut spare, FlushDecompress::None) + .unwrap(); + decoded.extend_from_slice(&spare); + status + }; + if status == Status::StreamEnd { + break; + } + assert_ne!((bi as u64, bo), (decoder.total_in(), decoder.total_out())); + step += 1; + } + assert_eq!(decoded, input); + assert_eq!(decoder.total_in() as usize, encoded.len()); + } +} + +fn decode_prefix(compressed: &[u8], input: &[u8]) { + let mut decoder = Decompress::new(false); + let mut output = vec![0; input.len() + 1]; + loop { + let (bi, bo) = (decoder.total_in(), decoder.total_out()); + let status = decoder + .decompress( + &compressed[bi as usize..], + &mut output[bo as usize..], + FlushDecompress::None, + ) + .unwrap(); + if status == Status::StreamEnd || (bi, bo) == (decoder.total_in(), decoder.total_out()) { + break; + } + } + assert_eq!(decoder.total_out() as usize, input.len()); + assert_eq!(&output[..input.len()], input); +} + +#[test] +fn writer_flush_exposes_every_input_byte() { + for level in [0, 1, 6, 9] { + for size in [32768, 65536, 100000, 131072, 524288] { + let input = random(size); + let mut encoder = + flate2::write::DeflateEncoder::new(Vec::new(), Compression::new(level)); + encoder.write_all(&input).unwrap(); + encoder.flush().unwrap(); + decode_prefix(encoder.get_ref(), &input); + } + } +} + +#[derive(Default)] +struct ShortWriter { + bytes: Vec, + calls: usize, + fail_at: usize, + interrupted: bool, +} +impl Write for ShortWriter { + fn write(&mut self, data: &[u8]) -> io::Result { + self.calls += 1; + if self.calls == self.fail_at { + return Err(io::ErrorKind::WouldBlock.into()); + } + if !self.interrupted { + self.interrupted = true; + return Err(io::ErrorKind::Interrupted.into()); + } + let n = data.len().min(7); + self.bytes.extend_from_slice(&data[..n]); + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn flush_retry_after_partial_writes_preserves_all_bytes() { + let input = random(100000); + for level in [0, 1, 6] { + let mut encoder = + flate2::write::DeflateEncoder::new(ShortWriter::default(), Compression::new(level)); + encoder.write_all(&input).unwrap(); + encoder.get_mut().fail_at = encoder.get_ref().calls + 3; + assert_eq!( + encoder.flush().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); + encoder.flush().unwrap(); + decode_prefix(&encoder.get_ref().bytes, &input); + decode_prefix(&encoder.finish().unwrap().bytes, &input); + } +}