From 1eba51bafe0b386e1b6884d07e1a9a42c9d62050 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Tue, 19 May 2026 13:12:18 +0100 Subject: [PATCH 01/10] Add fdeflate backend --- Cargo.toml | 4 + src/ffi/fdeflate.rs | 387 ++++++++++++++++++++++++++++++++++++++++++++ src/ffi/mod.rs | 18 ++- src/mem.rs | 13 +- tests/fdeflate.rs | 150 +++++++++++++++++ 5 files changed, 569 insertions(+), 3 deletions(-) create mode 100644 src/ffi/fdeflate.rs create mode 100644 tests/fdeflate.rs diff --git a/Cargo.toml b/Cargo.toml index 5853d792..ff39153b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ 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 } @@ -61,6 +62,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/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs new file mode 100644 index 00000000..aa4562da --- /dev/null +++ b/src/ffi/fdeflate.rs @@ -0,0 +1,387 @@ +//! Implementation for the `fdeflate` Rust backend. + +use std::fmt; +use std::io; + +use ::fdeflate::{DecompressionError as FdeflateError, FlushKind}; + +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; + +use super::*; +use crate::mem::{compress_failed, decompress_failed}; + +// fdeflate's decompressor needs one contiguous output slice containing recent history followed by +// writable space. Keeping 32 KiB of history plus a 64 KiB decode tail avoids copying the history on +// every call while still bounding how much decoded output we stage ahead of the caller. +const FDEFLATE_HISTORY_LEN: usize = 32 * 1024; +const FDEFLATE_DECODE_TAIL_LEN: usize = 64 * 1024; +const FDEFLATE_SCRATCH_LEN: usize = FDEFLATE_HISTORY_LEN + FDEFLATE_DECODE_TAIL_LEN; + +#[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 io_error_message(_: io::Error) -> ErrorMessage { + ErrorMessage(Some("fdeflate compression failed")) +} + +fn compression_result(result: io::Result) -> Result { + match result { + Ok(value) => Ok(value), + Err(error) => compress_failed(io_error_message(error)), + } +} + +fn new_compressor(level: u8, zlib_header: bool) -> ::fdeflate::Compressor> { + ::fdeflate::Compressor::new(Vec::new(), level, zlib_header) + .expect("writing fdeflate output to a Vec cannot fail") +} + +fn drain_vec(pending: &mut Vec, pending_pos: &mut usize, output: &mut [u8]) -> usize { + let n = (pending.len() - *pending_pos).min(output.len()); + output[..n].copy_from_slice(&pending[*pending_pos..*pending_pos + n]); + *pending_pos += n; + if *pending_pos == pending.len() { + pending.clear(); + *pending_pos = 0; + } + n +} + +pub struct Deflate { + inner: Option<::fdeflate::Compressor>>, + pending: Vec, + pending_pos: usize, + inner_pending_pos: usize, + level: u8, + zlib_header: bool, + total_in: u64, + total_out: u64, +} + +impl fmt::Debug for Deflate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!( + f, + "fdeflate deflate internal state. total_in: {}, total_out: {}", + self.total_in, self.total_out, + ) + } +} + +impl Deflate { + fn drain_pending(&mut self, output: &mut [u8]) -> usize { + let mut output_index = drain_vec(&mut self.pending, &mut self.pending_pos, output); + + if output_index < output.len() { + if let Some(ref mut inner) = self.inner { + // fdeflate writes into the wrapped Vec; flate2 callers own the real destination, so + // drain those pending bytes before accepting more input. Track a cursor instead of + // draining the Vec so small caller buffers do not force repeated memmoves. + output_index += drain_vec( + inner.get_mut(), + &mut self.inner_pending_pos, + &mut output[output_index..], + ); + } + } + + self.total_out += output_index as u64; + output_index + } + + fn is_finished(&self) -> bool { + self.inner.is_none() && self.pending.is_empty() + } +} + +impl DeflateBackend for Deflate { + fn make(level: Compression, zlib_header: bool, _window_bits: u8) -> Self { + let level = level.level().min(9) as u8; + Deflate { + inner: Some(new_compressor(level, zlib_header)), + pending: Vec::new(), + pending_pos: 0, + inner_pending_pos: 0, + level, + zlib_header, + total_in: 0, + total_out: 0, + } + } + + fn compress( + &mut self, + input: &[u8], + output: &mut [u8], + flush: FlushCompress, + ) -> Result { + let before_in = self.total_in; + let before_out = self.total_out; + + let output_index = self.drain_pending(output); + if output_index == output.len() { + return if self.is_finished() { + Ok(Status::StreamEnd) + } else if output.is_empty() { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + }; + } + + if self.inner.is_none() { + return Ok(Status::StreamEnd); + } + + if let Some(ref mut inner) = self.inner { + if !input.is_empty() { + compression_result(inner.write_data(input))?; + self.total_in += input.len() as u64; + } + + match flush { + FlushCompress::None => {} + FlushCompress::Partial => compression_result(inner.flush(FlushKind::Partial))?, + FlushCompress::Sync => compression_result(inner.flush(FlushKind::Sync))?, + FlushCompress::Full => compression_result(inner.flush(FlushKind::Full))?, + FlushCompress::Finish => { + let inner = self.inner.take().unwrap(); + self.pending = compression_result(inner.finish())?; + self.pending_pos = 0; + self.inner_pending_pos = 0; + } + } + } + + self.drain_pending(&mut output[output_index..]); + + if self.is_finished() { + Ok(Status::StreamEnd) + } else if before_in == self.total_in && before_out == self.total_out { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + } + } + + fn reset(&mut self) { + self.inner = Some(new_compressor(self.level, self.zlib_header)); + self.pending.clear(); + self.pending_pos = 0; + self.inner_pending_pos = 0; + self.total_in = 0; + self.total_out = 0; + } +} + +impl Backend for Deflate { + #[inline] + fn total_in(&self) -> u64 { + self.total_in + } + + #[inline] + fn total_out(&self) -> u64 { + self.total_out + } +} + +pub struct Inflate { + inner: ::fdeflate::Decompressor, + scratch: Vec, + drain_pos: usize, + decode_pos: usize, + total_in: u64, + total_out: u64, + done: bool, +} + +impl fmt::Debug for Inflate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!( + f, + "fdeflate inflate internal state. total_in: {}, total_out: {}", + self.total_in, self.total_out, + ) + } +} + +impl Inflate { + fn has_pending_output(&self) -> bool { + self.drain_pos < self.decode_pos + } + + fn drain_output(&mut self, output: &mut [u8]) -> usize { + let n = (self.decode_pos - self.drain_pos).min(output.len()); + output[..n].copy_from_slice(&self.scratch[self.drain_pos..self.drain_pos + n]); + self.drain_pos += n; + self.total_out += n as u64; + n + } + + fn compact_if_needed(&mut self) { + debug_assert!(!self.has_pending_output()); + + if self.decode_pos + FDEFLATE_DECODE_TAIL_LEN <= self.scratch.len() { + return; + } + + // A VecDeque would avoid this occasional copy, but fdeflate needs a single contiguous + // slice containing both lookback history and writable output. Once the staged output has + // been drained, keep only the 32 KiB deflate history and reopen the 64 KiB decode tail. + let keep = self.decode_pos.min(FDEFLATE_HISTORY_LEN); + let start = self.decode_pos - keep; + if start != 0 { + self.scratch.copy_within(start..self.decode_pos, 0); + } + self.drain_pos = keep; + self.decode_pos = keep; + } +} + +impl InflateBackend for Inflate { + fn make(zlib_header: bool, _window_bits: u8) -> Self { + let format = format_from_bool(zlib_header); + Inflate { + inner: ::fdeflate::Decompressor::new_with_format(format), + scratch: vec![0; FDEFLATE_SCRATCH_LEN], + drain_pos: 0, + decode_pos: 0, + total_in: 0, + total_out: 0, + done: false, + } + } + + fn decompress( + &mut self, + input: &[u8], + output: &mut [u8], + _flush: FlushDecompress, + ) -> Result { + let before_in = self.total_in; + let before_out = self.total_out; + + // Always drain staged output first. This keeps the scratch buffer from accumulating more + // than the tunable 64 KiB decode tail when callers provide very small output buffers. + let output_index = self.drain_output(output); + if output_index == output.len() { + return if self.done && !self.has_pending_output() { + Ok(Status::StreamEnd) + } else if output.is_empty() { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + }; + } + + if self.done { + return Ok(Status::StreamEnd); + } + + self.compact_if_needed(); + + let mut input_index = 0; + loop { + let target_end = (self.decode_pos + FDEFLATE_DECODE_TAIL_LEN).min(self.scratch.len()); + if self.decode_pos == target_end { + break; + } + + let (consumed, produced) = match self.inner.read( + &input[input_index..], + &mut self.scratch[..target_end], + self.decode_pos, + ) { + Ok(result) => result, + Err(error) => { + return decompress_failed(ErrorMessage(Some(decompression_message(error)))); + } + }; + input_index += consumed; + self.total_in += consumed as u64; + self.decode_pos += produced; + self.done = self.inner.is_done(); + + // fdeflate may need one more turn after producing output to consume the final EOF + // marker from its bit buffer. Keep decoding into the contiguous tail until there is + // no internal progress left, the stream ends, or the staging tail is full. + if self.done || (consumed == 0 && produced == 0) { + break; + } + } + + self.drain_output(&mut output[output_index..]); + + if self.done && !self.has_pending_output() { + Ok(Status::StreamEnd) + } else if before_in == self.total_in && before_out == self.total_out { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + } + } + + fn reset(&mut self, zlib_header: bool) { + let format = format_from_bool(zlib_header); + self.inner.reset(format); + self.drain_pos = 0; + self.decode_pos = 0; + self.total_in = 0; + self.total_out = 0; + self.done = false; + } +} + +impl Backend for Inflate { + #[inline] + fn total_in(&self) -> u64 { + self.total_in + } + + #[inline] + 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..bdc06597 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, @@ -665,6 +669,7 @@ mod tests { use crate::write; use crate::{Compression, Decompress, FlushDecompress}; + #[cfg(not(feature = "fdeflate"))] use crate::{Compress, FlushCompress}; #[test] @@ -815,6 +820,9 @@ mod tests { assert_eq!(err.message(), Some("invalid stored block lengths")); } + // TODO: Re-enable these flush byte-layout tests for fdeflate once + // https://github.com/image-rs/fdeflate/pull/73 is available in the dependency. + #[cfg(not(feature = "fdeflate"))] fn compress_with_flush(flush: FlushCompress) -> Vec { let incompressible = (0..=255).collect::>(); let mut output = vec![0; 1024]; @@ -848,6 +856,7 @@ mod tests { output } + #[cfg(not(feature = "fdeflate"))] #[test] fn test_partial_flush() { let output = compress_with_flush(FlushCompress::Partial); @@ -857,6 +866,7 @@ mod tests { assert_eq!(output[262] & 0x7, 0x4); } + #[cfg(not(feature = "fdeflate"))] #[test] fn test_sync_flush() { let output = compress_with_flush(FlushCompress::Sync); @@ -865,6 +875,7 @@ mod tests { assert_eq!(&output[261..][..5], &[0, 0, 0, 0xff, 0xff]); } + #[cfg(not(feature = "fdeflate"))] #[test] fn test_full_flush() { let output = compress_with_flush(FlushCompress::Full); diff --git a/tests/fdeflate.rs b/tests/fdeflate.rs new file mode 100644 index 00000000..89e78e67 --- /dev/null +++ b/tests/fdeflate.rs @@ -0,0 +1,150 @@ +#![cfg(feature = "fdeflate")] + +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 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); +} From f920098212282745d10e6084b2b8c03150ba5819 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Tue, 19 May 2026 13:27:10 +0100 Subject: [PATCH 02/10] Limit fdeflate input per compress call --- src/ffi/fdeflate.rs | 40 +++++++++++++++++++++++++++------------- tests/fdeflate.rs | 21 +++++++++++++++++++++ 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs index aa4562da..1df84431 100644 --- a/src/ffi/fdeflate.rs +++ b/src/ffi/fdeflate.rs @@ -23,6 +23,11 @@ const FDEFLATE_HISTORY_LEN: usize = 32 * 1024; const FDEFLATE_DECODE_TAIL_LEN: usize = 64 * 1024; const FDEFLATE_SCRATCH_LEN: usize = FDEFLATE_HISTORY_LEN + FDEFLATE_DECODE_TAIL_LEN; +// fdeflate compresses into its wrapped writer, not directly into flate2's caller-provided output +// slice. Capping fresh input per call keeps that wrapped Vec from growing with arbitrarily large +// caller slices while still amortizing fdeflate's block/parser overhead. +const FDEFLATE_ENCODE_INPUT_CHUNK_LEN: usize = 128 * 1024; + #[derive(Clone, Default)] pub struct ErrorMessage(Option<&'static str>); @@ -174,22 +179,31 @@ impl DeflateBackend for Deflate { return Ok(Status::StreamEnd); } + let accepted_input_len = input.len().min(FDEFLATE_ENCODE_INPUT_CHUNK_LEN); + let accepted_all_input = accepted_input_len == input.len(); + if let Some(ref mut inner) = self.inner { - if !input.is_empty() { - compression_result(inner.write_data(input))?; - self.total_in += input.len() as u64; + if accepted_input_len != 0 { + let accepted_input = &input[..accepted_input_len]; + compression_result(inner.write_data(accepted_input))?; + self.total_in += accepted_input.len() as u64; } - match flush { - FlushCompress::None => {} - FlushCompress::Partial => compression_result(inner.flush(FlushKind::Partial))?, - FlushCompress::Sync => compression_result(inner.flush(FlushKind::Sync))?, - FlushCompress::Full => compression_result(inner.flush(FlushKind::Full))?, - FlushCompress::Finish => { - let inner = self.inner.take().unwrap(); - self.pending = compression_result(inner.finish())?; - self.pending_pos = 0; - self.inner_pending_pos = 0; + // A flush describes all input provided to this call. If we only accepted a prefix to + // preserve streaming backpressure, defer the flush until the caller comes back with the + // remaining input, just like other backends report partial consumption through total_in. + if accepted_all_input { + match flush { + FlushCompress::None => {} + FlushCompress::Partial => compression_result(inner.flush(FlushKind::Partial))?, + FlushCompress::Sync => compression_result(inner.flush(FlushKind::Sync))?, + FlushCompress::Full => compression_result(inner.flush(FlushKind::Full))?, + FlushCompress::Finish => { + let inner = self.inner.take().unwrap(); + self.pending = compression_result(inner.finish())?; + self.pending_pos = 0; + self.inner_pending_pos = 0; + } } } } diff --git a/tests/fdeflate.rs b/tests/fdeflate.rs index 89e78e67..7d89d4b9 100644 --- a/tests/fdeflate.rs +++ b/tests/fdeflate.rs @@ -75,6 +75,27 @@ fn raw_trailing_bytes_remain_unconsumed() { assert_eq!(&decoded[..decoder.total_out() as usize], input); } +#[test] +fn large_no_flush_call_preserves_streaming_backpressure() { + let input = vec![0x5a; 2 * 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"; From 7a9e1eb92e1f8f4870a6976e04bde30413a07cfb Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Tue, 19 May 2026 13:30:54 +0100 Subject: [PATCH 03/10] Add a CI job for the fdeflate backend --- .github/workflows/main.yml | 1 + 1 file changed, 1 insertion(+) 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: | From 4a763c16e0e1d1fc940ce42f29dd1824c0486c13 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sat, 17 Oct 2026 17:52:37 +0100 Subject: [PATCH 04/10] Use fdeflate's bounded streaming APIs in the backend The previous writer-to-Vec bridge capped input per call but could still retain unbounded parser data and encoded output. Its decoder stopped at internal scratch boundaries, so a sufficiently sized caller buffer could still receive an incomplete result. Error paths also lost consumed/produced accounting. Drive StreamingCompressor directly and map its progress to flate2 counters and statuses. Drain/decode repeatedly across the reusable 96 KiB scratch buffer, decode directly into large initialized destinations when history permits, and copy only initialized output into MaybeUninit destinations. Preserve terminal errors and trailing input, allow zero-output calls to finish empty streams and checksums, and reuse allocations on reset. Forbid unsafe code in this adapter. Add regressions for exact output sizes, one-call Finish, slice/Vec transitions, history across chunks, checksum errors, and trailing bytes. Re-enable existing flush byte-layout tests, and gate backend-specific tests on actual selection. The new APIs require the accompanying fdeflate series ending at c99a7578a082ba526252559b04e49fb4e58f7092. Keep a local Cargo patch while those commits are unpublished; the dependency branch must contain them before that override is removed. Document this setup and the std/Rust 1.88 requirement. no_std support remains deferred. Validation: the complete fdeflate-backend cargo test suite passed on an isolated export of this staged adapter, before the separate shared-writer changes. --- Cargo.toml | 5 + README.md | 12 ++ src/ffi/fdeflate.rs | 470 ++++++++++++++++++++------------------------ src/mem.rs | 7 - tests/fdeflate.rs | 27 ++- tests/streaming.rs | 178 +++++++++++++++++ 6 files changed, 437 insertions(+), 262 deletions(-) create mode 100644 tests/streaming.rs diff --git a/Cargo.toml b/Cargo.toml index ff39153b..7fdd1a60 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,11 @@ fdeflate = { git = "https://github.com/Shnatsel/fdeflate.git", branch = "flate2- crc32fast = { version = "1.2.0", default-features = false, optional = true } document-features = { version = "0.2", optional = true } +# Develop the streaming API together with the local fdeflate checkout. Remove this +# override once these dependency changes are available on flate2-api-changes. +[patch."https://github.com/Shnatsel/fdeflate.git"] +fdeflate = { path = "fdeflate" } + [dev-dependencies] futures = { version = "0.3", default-features = false } rand = "0.9" diff --git a/README.md b/README.md index 5ea3f5dc..49e957f3 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,18 @@ 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. + +Development currently uses the local `fdeflate/` checkout through a Cargo patch. +The changes in that checkout must accompany this adapter; remove the patch once +they are available on the dependency's `flate2-api-changes` branch. + ### C backends While zlib-rs is [the fastest overall](https://trifectatech.org/blog/zlib-rs-is-faster-than-c/), diff --git a/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs index 1df84431..28e7a58e 100644 --- a/src/ffi/fdeflate.rs +++ b/src/ffi/fdeflate.rs @@ -1,36 +1,28 @@ //! Implementation for the `fdeflate` Rust backend. +#![forbid(unsafe_code)] -use std::fmt; -use std::io; - -use ::fdeflate::{DecompressionError as FdeflateError, FlushKind}; +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; -use super::*; -use crate::mem::{compress_failed, decompress_failed}; - -// fdeflate's decompressor needs one contiguous output slice containing recent history followed by -// writable space. Keeping 32 KiB of history plus a 64 KiB decode tail avoids copying the history on -// every call while still bounding how much decoded output we stage ahead of the caller. -const FDEFLATE_HISTORY_LEN: usize = 32 * 1024; -const FDEFLATE_DECODE_TAIL_LEN: usize = 64 * 1024; -const FDEFLATE_SCRATCH_LEN: usize = FDEFLATE_HISTORY_LEN + FDEFLATE_DECODE_TAIL_LEN; - -// fdeflate compresses into its wrapped writer, not directly into flate2's caller-provided output -// slice. Capping fresh input per call keeps that wrapped Vec from growing with arbitrarily large -// caller slices while still amortizing fdeflate's block/parser overhead. -const FDEFLATE_ENCODE_INPUT_CHUNK_LEN: usize = 128 * 1024; +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 @@ -66,181 +58,118 @@ fn decompression_message(error: FdeflateError) -> &'static str { } } -fn io_error_message(_: io::Error) -> ErrorMessage { - ErrorMessage(Some("fdeflate compression failed")) -} - -fn compression_result(result: io::Result) -> Result { - match result { - Ok(value) => Ok(value), - Err(error) => compress_failed(io_error_message(error)), - } -} - -fn new_compressor(level: u8, zlib_header: bool) -> ::fdeflate::Compressor> { - ::fdeflate::Compressor::new(Vec::new(), level, zlib_header) - .expect("writing fdeflate output to a Vec cannot fail") -} - -fn drain_vec(pending: &mut Vec, pending_pos: &mut usize, output: &mut [u8]) -> usize { - let n = (pending.len() - *pending_pos).min(output.len()); - output[..n].copy_from_slice(&pending[*pending_pos..*pending_pos + n]); - *pending_pos += n; - if *pending_pos == pending.len() { - pending.clear(); - *pending_pos = 0; +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, } - n } pub struct Deflate { - inner: Option<::fdeflate::Compressor>>, - pending: Vec, - pending_pos: usize, - inner_pending_pos: usize, - level: u8, + inner: ::fdeflate::StreamingCompressor, zlib_header: bool, total_in: u64, total_out: u64, } - impl fmt::Debug for Deflate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - write!( - f, - "fdeflate deflate internal state. total_in: {}, total_out: {}", - self.total_in, self.total_out, - ) + 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 drain_pending(&mut self, output: &mut [u8]) -> usize { - let mut output_index = drain_vec(&mut self.pending, &mut self.pending_pos, output); - - if output_index < output.len() { - if let Some(ref mut inner) = self.inner { - // fdeflate writes into the wrapped Vec; flate2 callers own the real destination, so - // drain those pending bytes before accepting more input. Track a cursor instead of - // draining the Vec so small caller buffers do not force repeated memmoves. - output_index += drain_vec( - inner.get_mut(), - &mut self.inner_pending_pos, - &mut output[output_index..], - ); - } + 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), } - - self.total_out += output_index as u64; - output_index - } - - fn is_finished(&self) -> bool { - self.inner.is_none() && self.pending.is_empty() } } - impl DeflateBackend for Deflate { fn make(level: Compression, zlib_header: bool, _window_bits: u8) -> Self { - let level = level.level().min(9) as u8; - Deflate { - inner: Some(new_compressor(level, zlib_header)), - pending: Vec::new(), - pending_pos: 0, - inner_pending_pos: 0, - level, + 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 before_in = self.total_in; - let before_out = self.total_out; - - let output_index = self.drain_pending(output); - if output_index == output.len() { - return if self.is_finished() { - Ok(Status::StreamEnd) - } else if output.is_empty() { - Ok(Status::BufError) - } else { - Ok(Status::Ok) - }; - } - - if self.inner.is_none() { - return Ok(Status::StreamEnd); - } - - let accepted_input_len = input.len().min(FDEFLATE_ENCODE_INPUT_CHUNK_LEN); - let accepted_all_input = accepted_input_len == input.len(); - - if let Some(ref mut inner) = self.inner { - if accepted_input_len != 0 { - let accepted_input = &input[..accepted_input_len]; - compression_result(inner.write_data(accepted_input))?; - self.total_in += accepted_input.len() as u64; - } - - // A flush describes all input provided to this call. If we only accepted a prefix to - // preserve streaming backpressure, defer the flush until the caller comes back with the - // remaining input, just like other backends report partial consumption through total_in. - if accepted_all_input { - match flush { - FlushCompress::None => {} - FlushCompress::Partial => compression_result(inner.flush(FlushKind::Partial))?, - FlushCompress::Sync => compression_result(inner.flush(FlushKind::Sync))?, - FlushCompress::Full => compression_result(inner.flush(FlushKind::Full))?, - FlushCompress::Finish => { - let inner = self.inner.take().unwrap(); - self.pending = compression_result(inner.finish())?; - self.pending_pos = 0; - self.inner_pending_pos = 0; - } - } - } - } - - self.drain_pending(&mut output[output_index..]); - - if self.is_finished() { - Ok(Status::StreamEnd) - } else if before_in == self.total_in && before_out == self.total_out { - Ok(Status::BufError) - } else { - Ok(Status::Ok) - } + 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 = Some(new_compressor(self.level, self.zlib_header)); - self.pending.clear(); - self.pending_pos = 0; - self.inner_pending_pos = 0; + self.inner.reset(self.zlib_header); self.total_in = 0; self.total_out = 0; } } - impl Backend for Deflate { - #[inline] fn total_in(&self) -> u64 { self.total_in } - - #[inline] 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, @@ -249,152 +178,185 @@ pub struct Inflate { total_in: u64, total_out: u64, done: bool, + error: Option<&'static str>, } - impl fmt::Debug for Inflate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - write!( - f, - "fdeflate inflate internal state. total_in: {}, total_out: {}", - self.total_in, self.total_out, - ) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("fdeflate::Inflate") + .field("total_in", &self.total_in) + .field("total_out", &self.total_out) + .finish() } } - impl Inflate { - fn has_pending_output(&self) -> bool { - self.drain_pos < self.decode_pos - } - - fn drain_output(&mut self, output: &mut [u8]) -> usize { - let n = (self.decode_pos - self.drain_pos).min(output.len()); - output[..n].copy_from_slice(&self.scratch[self.drain_pos..self.drain_pos + n]); + 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; - n } - fn compact_if_needed(&mut self) { - debug_assert!(!self.has_pending_output()); - - if self.decode_pos + FDEFLATE_DECODE_TAIL_LEN <= self.scratch.len() { - return; - } - - // A VecDeque would avoid this occasional copy, but fdeflate needs a single contiguous - // slice containing both lookback history and writable output. Once the staged output has - // been drained, keep only the 32 KiB deflate history and reopen the 64 KiB decode tail. - let keep = self.decode_pos.min(FDEFLATE_HISTORY_LEN); - let start = self.decode_pos - keep; - if start != 0 { - self.scratch.copy_within(start..self.decode_pos, 0); + fn prepare_scratch(&mut self, writable: usize) { + if self.scratch.is_empty() { + self.scratch.resize(SCRATCH, 0); } - self.drain_pos = keep; - self.decode_pos = keep; - } -} - -impl InflateBackend for Inflate { - fn make(zlib_header: bool, _window_bits: u8) -> Self { - let format = format_from_bool(zlib_header); - Inflate { - inner: ::fdeflate::Decompressor::new_with_format(format), - scratch: vec![0; FDEFLATE_SCRATCH_LEN], - drain_pos: 0, - decode_pos: 0, - total_in: 0, - total_out: 0, - done: false, + 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 decompress( + fn run( &mut self, input: &[u8], - output: &mut [u8], - _flush: FlushDecompress, + output: &mut O, + flush: FlushDecompress, ) -> Result { - let before_in = self.total_in; - let before_out = self.total_out; - - // Always drain staged output first. This keeps the scratch buffer from accumulating more - // than the tunable 64 KiB decode tail when callers provide very small output buffers. - let output_index = self.drain_output(output); - if output_index == output.len() { - return if self.done && !self.has_pending_output() { - Ok(Status::StreamEnd) - } else if output.is_empty() { - Ok(Status::BufError) - } else { - Ok(Status::Ok) - }; + if let Some(error) = self.error { + return decompress_failed(ErrorMessage(Some(error))); } - - if self.done { - return Ok(Status::StreamEnd); - } - - self.compact_if_needed(); - - let mut input_index = 0; + let before = (self.total_in, self.total_out); + let mut input_pos = 0; + let mut output_pos = 0; loop { - let target_end = (self.decode_pos + FDEFLATE_DECODE_TAIL_LEN).min(self.scratch.len()); - if self.decode_pos == target_end { + self.drain(output, &mut output_pos); + if self.drain_pos != self.decode_pos || self.done { break; } - let (consumed, produced) = match self.inner.read( - &input[input_index..], - &mut self.scratch[..target_end], + // 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, - ) { - Ok(result) => result, + ); + 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) => { - return decompress_failed(ErrorMessage(Some(decompression_message(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; + } } - }; - input_index += consumed; - self.total_in += consumed as u64; - self.decode_pos += produced; - self.done = self.inner.is_done(); - - // fdeflate may need one more turn after producing output to consume the final EOF - // marker from its bit buffer. Keep decoding into the contiguous tail until there is - // no internal progress left, the stream ends, or the staging tail is full. - if self.done || (consumed == 0 && produced == 0) { - break; } } - - self.drain_output(&mut output[output_index..]); - - if self.done && !self.has_pending_output() { + if self.done && self.drain_pos == self.decode_pos { Ok(Status::StreamEnd) - } else if before_in == self.total_in && before_out == self.total_out { + } 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) { - let format = format_from_bool(zlib_header); - self.inner.reset(format); + 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 { - #[inline] fn total_in(&self) -> u64 { self.total_in } - - #[inline] fn total_out(&self) -> u64 { self.total_out } diff --git a/src/mem.rs b/src/mem.rs index bdc06597..278cb37f 100644 --- a/src/mem.rs +++ b/src/mem.rs @@ -669,7 +669,6 @@ mod tests { use crate::write; use crate::{Compression, Decompress, FlushDecompress}; - #[cfg(not(feature = "fdeflate"))] use crate::{Compress, FlushCompress}; #[test] @@ -820,9 +819,6 @@ mod tests { assert_eq!(err.message(), Some("invalid stored block lengths")); } - // TODO: Re-enable these flush byte-layout tests for fdeflate once - // https://github.com/image-rs/fdeflate/pull/73 is available in the dependency. - #[cfg(not(feature = "fdeflate"))] fn compress_with_flush(flush: FlushCompress) -> Vec { let incompressible = (0..=255).collect::>(); let mut output = vec![0; 1024]; @@ -856,7 +852,6 @@ mod tests { output } - #[cfg(not(feature = "fdeflate"))] #[test] fn test_partial_flush() { let output = compress_with_flush(FlushCompress::Partial); @@ -866,7 +861,6 @@ mod tests { assert_eq!(output[262] & 0x7, 0x4); } - #[cfg(not(feature = "fdeflate"))] #[test] fn test_sync_flush() { let output = compress_with_flush(FlushCompress::Sync); @@ -875,7 +869,6 @@ mod tests { assert_eq!(&output[261..][..5], &[0, 0, 0, 0xff, 0xff]); } - #[cfg(not(feature = "fdeflate"))] #[test] fn test_full_flush() { let output = compress_with_flush(FlushCompress::Full); diff --git a/tests/fdeflate.rs b/tests/fdeflate.rs index 7d89d4b9..71bfcf09 100644 --- a/tests/fdeflate.rs +++ b/tests/fdeflate.rs @@ -1,4 +1,4 @@ -#![cfg(feature = "fdeflate")] +#![cfg(all(feature = "fdeflate", not(feature = "any_zlib")))] use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; use std::io::{Read, Write}; @@ -169,3 +169,28 @@ fn read_and_write_wrappers_roundtrip_single_zero() { 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.rs b/tests/streaming.rs new file mode 100644 index 00000000..ee7567ed --- /dev/null +++ b/tests/streaming.rs @@ -0,0 +1,178 @@ +//! Streaming contracts shared by all backends. +use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; + +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()); + } +} From 0006989e414acf5dc11d8a3f84942d132bbddb6f Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sat, 17 Oct 2026 17:52:44 +0100 Subject: [PATCH 05/10] Complete writer flushes and retain progress across short writes A codec can have pending output when Write::flush requests Sync. In particular, miniz may return a short buffer after draining old bytes without processing that new flush request, leaving accepted input invisible to a decoder. Issuing the flush into an already occupied output buffer also obscured completion. Drain existing codec output before requesting Sync with a fresh buffer, and repeat if the result fills that buffer. Respect StreamEnd and flush the wrapped writer after all encoded bytes have been delivered. Track a cursor into pending writer output instead of repeatedly draining the front of its Vec. This avoids moving the remaining bytes after every short write, retries Interrupted, and preserves progress across a WouldBlock error. Reset the cursor when the buffer is drained or the writer is replaced. Add regressions proving that flushing makes every input byte decodable across levels and boundary sizes, and that a retry after partial writes, Interrupted, and WouldBlock preserves the stream. Validation on an isolated staged tree: the full default/miniz suite passed; all six streaming tests also passed with fdeflate, fdeflate+zlib-rs, and fdeflate+zlib (exercising backend precedence as well as the shared writer). --- src/zio.rs | 57 +++++++++++++++++++++----------- tests/streaming.rs | 81 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 118 insertions(+), 20 deletions(-) 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/streaming.rs b/tests/streaming.rs index ee7567ed..695102c0 100644 --- a/tests/streaming.rs +++ b/tests/streaming.rs @@ -1,5 +1,6 @@ -//! Streaming contracts shared by all backends. +//! 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; @@ -176,3 +177,81 @@ fn alternating_slice_and_vec_output_preserves_decoder_history() { 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); + } +} From a7a3a117886ac37347fcc6b7866865533271c655 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sat, 17 Oct 2026 17:52:50 +0100 Subject: [PATCH 06/10] Add differential streaming fuzzing and deterministic regressions The buffering changes need coverage beyond successful one-shot round trips: flush schedules, zero-sized destinations, unfinished resets, malformed input, and truncation can expose counter, history, and progress bugs. Share one exercise harness between a deterministic size/pattern/level matrix and a libFuzzer target. Compare encoded streams and successful decodes with miniz_oxide, bound decoding work on malformed inputs, and check consumption, output limits, and forward progress through changing chunk sizes and flushes. Reset both codecs after partial work or an error before testing fresh streams. Gate the malformed-input and unfinished-reset matrix on fdeflate actually being selected: other backends have independent differences in those cases. Add the independent decoder as a dev/fuzz dependency, expose the fdeflate fuzz feature, and repeat the local dependency patch in the fuzz workspace. Validation on an isolated staged tree: the deterministic matrix passed and cargo check built the streaming fuzz target with the fdeflate feature. Earlier implementation validation also completed a 30-second nightly libFuzzer run (2,481 executions) without a failure. The regular streaming contract tests remain enabled for every backend. --- Cargo.toml | 1 + fuzz/Cargo.toml | 13 +++ fuzz/fuzz_targets/streaming.rs | 4 + fuzz/streaming.rs | 152 +++++++++++++++++++++++++++++++++ tests/streaming-random.rs | 34 ++++++++ 5 files changed, 204 insertions(+) create mode 100644 fuzz/fuzz_targets/streaming.rs create mode 100644 fuzz/streaming.rs create mode 100644 tests/streaming-random.rs diff --git a/Cargo.toml b/Cargo.toml index 7fdd1a60..7697242f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ document-features = { version = "0.2", optional = true } fdeflate = { path = "fdeflate" } [dev-dependencies] +miniz_oxide = "0.9.0" futures = { version = "0.3", default-features = false } rand = "0.9" quickcheck = { version = "1.0", default-features = false } diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 8defdd26..fc8b97d9 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -12,6 +12,13 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" flate2 = { path = ".." } +miniz_oxide = "0.9.0" + +[features] +fdeflate = ["flate2/fdeflate"] + +[patch."https://github.com/Shnatsel/fdeflate.git"] +fdeflate = { path = "../fdeflate" } # Prevent this from interfering with workspaces [workspace] @@ -22,3 +29,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/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); + } + } + } +} From a79fdd4c57071700117fca04944116ea5813f64f Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sat, 17 Oct 2026 17:55:04 +0100 Subject: [PATCH 07/10] Include inflater state in fdeflate Debug output Inflate's Debug implementation only reported byte counters, hiding the buffered-output positions and terminal state needed to diagnose streaming behavior. Include drain_pos, decode_pos, done, and error alongside total_in and total_out. Keep inner and scratch omitted so diagnostics do not dump the decoder internals or buffer contents. This changes diagnostic output only. Validation: cargo check --no-default-features --features fdeflate --offline, cargo fmt --all -- --check, and git diff --check passed. --- src/ffi/fdeflate.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs index 28e7a58e..59460a51 100644 --- a/src/ffi/fdeflate.rs +++ b/src/ffi/fdeflate.rs @@ -183,8 +183,12 @@ pub struct Inflate { 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() } } From c90cada0dd4712323c2fca3261eb4c36bc4eeef3 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sat, 17 Oct 2026 19:01:35 +0100 Subject: [PATCH 08/10] Exercise backpressure beyond fdeflate's token-buffer capacity A bounded token buffer can describe several MiB of repeated input before it must emit a DEFLATE block. The adapter test previously supplied 2 MiB and assumed that one byte of output space must stop input consumption, which is no longer true when the input fits in pending match tokens. Use 8 MiB of repeated input so the test crosses the token limit. Retain the assertions for partial consumption, output progress and decoding of the finished stream. This tests backpressure without imposing the old 128 KiB Huffman block boundary on the backend. Validation: cargo test --offline --release --no-default-features --features fdeflate passed the unit, integration and documentation tests with the token-budget implementation and without the RLE optimization. --- tests/fdeflate.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/fdeflate.rs b/tests/fdeflate.rs index 71bfcf09..9b44dbaa 100644 --- a/tests/fdeflate.rs +++ b/tests/fdeflate.rs @@ -77,7 +77,9 @@ fn raw_trailing_bytes_remain_unconsumed() { #[test] fn large_no_flush_call_preserves_streaming_backpressure() { - let input = vec![0x5a; 2 * 1024 * 1024]; + // 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); From 112b3acfd2e0fc4122f1f7c1e127d8c4a51e7523 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sat, 17 Oct 2026 19:01:45 +0100 Subject: [PATCH 09/10] Add source and low-entropy compression benchmarks The streaming microbenchmarks emphasize random or highly repetitive inputs and do not expose all costs of retaining tokens across batches. Add a compression-only corpus harness for local Rust-source and executable snapshots, plus deterministic low-alphabet and skewed byte distributions. Measure levels 1, 4, 6 and 9 with a zlib wrapper and 32 KiB output slices. Reuse the compressor and output allocation, include reset costs, warm up each case, and report the median of five samples lasting at least 50 ms. Emit elapsed time and compressed size as CSV so throughput improvements can be considered alongside ratio changes. Source/executable snapshots are supplied by the caller and are not checked into the repository. Validation: the harness was run across all four workloads and levels in the before/after token-budget comparison. It also compiles in the passing fdeflate-backend release test suite; formatting checks passed. --- examples/corpus_bench.rs | 76 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 examples/corpus_bench.rs 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]); + } + } +} From c459f060099250449feea25fc3a5eebbd86df6e6 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 22 Oct 2026 16:39:18 +0100 Subject: [PATCH 10/10] Repoint to my git version of fdeflate --- Cargo.toml | 5 ----- README.md | 4 ---- fuzz/Cargo.toml | 3 --- 3 files changed, 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7697242f..dbbb369e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,11 +29,6 @@ fdeflate = { git = "https://github.com/Shnatsel/fdeflate.git", branch = "flate2- crc32fast = { version = "1.2.0", default-features = false, optional = true } document-features = { version = "0.2", optional = true } -# Develop the streaming API together with the local fdeflate checkout. Remove this -# override once these dependency changes are available on flate2-api-changes. -[patch."https://github.com/Shnatsel/fdeflate.git"] -fdeflate = { path = "fdeflate" } - [dev-dependencies] miniz_oxide = "0.9.0" futures = { version = "0.3", default-features = false } diff --git a/README.md b/README.md index 49e957f3..2bedf43a 100644 --- a/README.md +++ b/README.md @@ -93,10 +93,6 @@ 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. -Development currently uses the local `fdeflate/` checkout through a Cargo patch. -The changes in that checkout must accompany this adapter; remove the patch once -they are available on the dependency's `flate2-api-changes` branch. - ### C backends While zlib-rs is [the fastest overall](https://trifectatech.org/blog/zlib-rs-is-faster-than-c/), diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index fc8b97d9..cf33db0d 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -17,9 +17,6 @@ miniz_oxide = "0.9.0" [features] fdeflate = ["flate2/fdeflate"] -[patch."https://github.com/Shnatsel/fdeflate.git"] -fdeflate = { path = "../fdeflate" } - # Prevent this from interfering with workspaces [workspace] members = ["."]