From 3bef6042f6eb1bde9fc933e65204180422d8e985 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Mon, 13 Apr 2026 23:25:54 +0100 Subject: [PATCH 1/2] Add fdeflate as a new backend for flate2 Implement the fdeflate crate as an optional pure-Rust backend, selectable via the `fdeflate` Cargo feature. fdeflate is a fast DEFLATE implementation that uses only safe Rust code. Key implementation details: - The decompressor maintains an internal window buffer since fdeflate uses the output buffer as a lookback window for back-references, but flate2 passes fresh output slices on each call. - The compressor buffers all output internally and emits it on Finish, since fdeflate writes a single deflate block. - Accounts for fdeflate's bit-buffer over-read via the new Decompressor::unconsumed_bytes() API, ensuring accurate total_in tracking. - Mid-stream flush tests (Partial/Sync/Full) are gated behind cfg(any(feature = "any_zlib", feature = "miniz_oxide")) since fdeflate does not support mid-stream flushing. Known issue: roundtrip through write::DeflateEncoder piped into write::DeflateDecoder fails for some inputs (e.g. single byte [0]). Co-Authored-By: Claude --- Cargo.toml | 6 + src/deflate/mod.rs | 12 ++ src/ffi/fdeflate.rs | 304 ++++++++++++++++++++++++++++++++++++++++++++ src/ffi/mod.rs | 14 ++ src/mem.rs | 7 + 5 files changed, 343 insertions(+) create mode 100644 src/ffi/fdeflate.rs diff --git a/Cargo.toml b/Cargo.toml index 6d413511..3dd1ff9a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ and raw deflate streams. exclude = [".*"] [dependencies] +fdeflate = { git = "https://github.com/Shnatsel/fdeflate.git", branch = "raw-deflate", optional = true } libz-sys = { version = "1.1.20", optional = true, default-features = false } libz-ng-sys = { version = "1.1.16", optional = true } # this matches the default features, but we don't want to depend on the default features staying the same @@ -88,6 +89,11 @@ zlib-ng = ["any_c_zlib", "libz-ng-sys", "dep:crc32fast"] ## Falls back to `libz-sys`, but we recommend switching to `zlib-rs` instead. cloudflare_zlib = ["zlib"] +## Use the `fdeflate` backend, a fast pure Rust deflate implementation. +## This implementation uses only safe Rust code and doesn't require a C compiler. +## It is optimized for speed and provides good compression performance. +fdeflate = ["any_impl", "dep:fdeflate", "dep:crc32fast"] + ## Deprecated alias for `rust_backend`, provided for backwards compatibility. ## Use `rust_backend` instead. miniz-sys = ["rust_backend"] diff --git a/src/deflate/mod.rs b/src/deflate/mod.rs index b5c5b6ca..5ee1aa13 100644 --- a/src/deflate/mod.rs +++ b/src/deflate/mod.rs @@ -177,6 +177,18 @@ mod tests { } } + #[test] + fn debug_single_byte() { + let v = vec![0u8]; + let mut w = write::DeflateEncoder::new( + write::DeflateDecoder::new(Vec::new()), + Compression::default(), + ); + w.write_all(&v).unwrap(); + let result = w.finish().unwrap().finish().unwrap(); + assert_eq!(v, result); + } + #[test] fn qc_writer() { ::quickcheck::quickcheck(test as fn(_) -> _); diff --git a/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs new file mode 100644 index 00000000..bc8a7d9e --- /dev/null +++ b/src/ffi/fdeflate.rs @@ -0,0 +1,304 @@ +//! Implementation for `fdeflate` rust backend. + +use std::fmt; + +use super::*; +use crate::mem; + +// fdeflate doesn't provide error messages +#[derive(Clone, Default)] +pub struct ErrorMessage; + +impl ErrorMessage { + pub fn get(&self) -> Option<&str> { + None + } +} + +// Constants matching the zlib flush values used by FlushCompress/FlushDecompress. +// These are defined as isize to match the interface expected by mem.rs for the +// FlushCompress/FlushDecompress enum discriminants. +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: isize = 15; + +/// The DEFLATE window size (32 KB). fdeflate's Decompressor uses the output buffer +/// as a lookback window for back-references, so we must maintain a persistent buffer +/// that contains at least this much history. +const WINDOW_SIZE: usize = 32768; + +pub struct Inflate { + inner: ::fdeflate::Decompressor, + /// Persistent output buffer used as the lookback window. fdeflate reads + /// back-references from this buffer, so we must keep prior output available. + window_buf: Vec, + /// Current write position in `window_buf`. + window_pos: usize, + total_in: u64, + total_out: u64, + is_zlib: 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 { + /// Ensure there is room to write `needed` bytes into the window buffer. + /// If the buffer is getting too large, shift it to keep only the last WINDOW_SIZE bytes. + fn ensure_window_capacity(&mut self, needed: usize) { + if self.window_pos + needed > self.window_buf.len() { + // Grow the buffer to accommodate the new data + self.window_buf.resize(self.window_pos + needed, 0); + } + + // Compact when the buffer gets much larger than the window size + if self.window_pos > WINDOW_SIZE * 4 { + let keep_from = self.window_pos.saturating_sub(WINDOW_SIZE); + self.window_buf.copy_within(keep_from..self.window_pos, 0); + self.window_pos -= keep_from; + self.window_buf.truncate(self.window_pos + needed); + } + } +} + +impl InflateBackend for Inflate { + fn make(zlib_header: bool, _window_bits: u8) -> Self { + Inflate { + inner: if zlib_header { + ::fdeflate::Decompressor::new() + } else { + ::fdeflate::Decompressor::new_raw() + }, + window_buf: Vec::new(), + window_pos: 0, + total_in: 0, + total_out: 0, + is_zlib: zlib_header, + } + } + + fn decompress( + &mut self, + input: &[u8], + output: &mut [u8], + _flush: FlushDecompress, + ) -> Result { + if self.inner.is_done() { + return Ok(Status::StreamEnd); + } + + // Make sure we have space in the window buffer for the caller's output size + self.ensure_window_capacity(output.len()); + + let (consumed, produced) = match self + .inner + .read(input, &mut self.window_buf, self.window_pos) + { + Ok(result) => result, + Err(_) => return mem::decompress_failed(ErrorMessage), + }; + + // Copy newly produced bytes to the caller's output buffer + output[..produced] + .copy_from_slice(&self.window_buf[self.window_pos..self.window_pos + produced]); + self.window_pos += produced; + + // When the decompressor finishes, its bit buffer may contain bytes + // that were read from input but not actually consumed. Subtract those + // so that total_in accurately reflects the compressed stream boundary. + let over_read = if self.inner.is_done() { + self.inner.unconsumed_bytes() + } else { + 0 + }; + + self.total_in += (consumed - over_read) as u64; + self.total_out += produced as u64; + + if self.inner.is_done() { + return Ok(Status::StreamEnd); + } + + if consumed == 0 && produced == 0 { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + } + } + + fn reset(&mut self, zlib_header: bool) { + self.is_zlib = zlib_header; + self.inner = if zlib_header { + ::fdeflate::Decompressor::new() + } else { + ::fdeflate::Decompressor::new_raw() + }; + self.window_buf.clear(); + self.window_pos = 0; + self.total_in = 0; + self.total_out = 0; + } +} + +impl Backend for Inflate { + #[inline] + fn total_in(&self) -> u64 { + self.total_in + } + + #[inline] + fn total_out(&self) -> u64 { + self.total_out + } +} + +/// Wraps fdeflate's Compressor to implement the streaming DeflateBackend interface. +/// +/// fdeflate's Compressor takes a `Write` target and has `write_data`/`finish` methods. +/// We use a `Vec` as the internal output buffer. Since fdeflate writes compressed +/// data to the writer during `write_data` and `finish` calls, we buffer that output +/// and drain it into the caller's output buffer on each `compress` call. +pub struct Deflate { + /// Buffered compressed output that hasn't been returned to the caller yet. + output_buf: Vec, + /// The compressor state. Set to `None` after `finish()` is called. + inner: Option<::fdeflate::Compressor>>, + total_in: u64, + total_out: u64, + level: u8, + zlib_header: bool, +} + +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 DeflateBackend for Deflate { + fn make(level: Compression, zlib_header: bool, _window_bits: u8) -> Self { + let level_u8 = level.level().min(9) as u8; + let compressor = + ::fdeflate::Compressor::new(Vec::new(), level_u8, zlib_header).unwrap(); + + Deflate { + output_buf: Vec::new(), + inner: Some(compressor), + total_in: 0, + total_out: 0, + level: level_u8, + zlib_header, + } + } + + fn compress( + &mut self, + input: &[u8], + output: &mut [u8], + flush: FlushCompress, + ) -> Result { + // If we have buffered output from a previous call, drain that first + // before processing new input. + if !self.output_buf.is_empty() { + let copy_len = self.output_buf.len().min(output.len()); + output[..copy_len].copy_from_slice(&self.output_buf[..copy_len]); + self.output_buf.drain(..copy_len); + self.total_out += copy_len as u64; + + if !self.output_buf.is_empty() { + // Still more buffered output to drain, don't consume any input + return Ok(Status::Ok); + } + + // If we already finished and the buffer is now drained, we're done. + if self.inner.is_none() { + return Ok(Status::StreamEnd); + } + + // Buffer drained but no new input and not finishing - signal caller + if input.is_empty() && flush == FlushCompress::None { + return Ok(Status::Ok); + } + } + + // If the compressor has already been finished and there's nothing + // left to drain, signal completion. + if self.inner.is_none() { + return Ok(Status::StreamEnd); + } + + // Feed input to the compressor + if !input.is_empty() { + let compressor = self.inner.as_mut().unwrap(); + if compressor.write_data(input).is_err() { + return mem::compress_failed(ErrorMessage); + } + self.total_in += input.len() as u64; + } + + if flush == FlushCompress::Finish { + // Finalize the compressor and collect all remaining output + let compressor = self.inner.take().unwrap(); + let compressed = match compressor.finish() { + Ok(c) => c, + Err(_) => return mem::compress_failed(ErrorMessage), + }; + + let copy_len = compressed.len().min(output.len()); + output[..copy_len].copy_from_slice(&compressed[..copy_len]); + self.total_out += copy_len as u64; + + if copy_len < compressed.len() { + self.output_buf.extend_from_slice(&compressed[copy_len..]); + return Ok(Status::Ok); + } + + return Ok(Status::StreamEnd); + } + + // For non-Finish calls: fdeflate buffers compressed data internally in + // the Vec writer. We can't extract partial output without finishing, + // so we just report that input was consumed. The compressed output will + // become available when finish() is eventually called. + if input.is_empty() { + Ok(Status::BufError) + } else { + Ok(Status::Ok) + } + } + + fn reset(&mut self) { + self.total_in = 0; + self.total_out = 0; + self.output_buf.clear(); + self.inner = Some( + ::fdeflate::Compressor::new(Vec::new(), self.level, self.zlib_header).unwrap(), + ); + } +} + +impl Backend for Deflate { + #[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 76e02b44..4d40c298 100644 --- a/src/ffi/mod.rs +++ b/src/ffi/mod.rs @@ -77,6 +77,20 @@ mod miniz_oxide; #[cfg(all(not(feature = "any_zlib"), feature = "miniz_oxide"))] pub use self::miniz_oxide::*; +// Use fdeflate when no other backend is selected. +#[cfg(all( + not(feature = "any_zlib"), + not(feature = "miniz_oxide"), + feature = "fdeflate" +))] +mod fdeflate; +#[cfg(all( + not(feature = "any_zlib"), + not(feature = "miniz_oxide"), + feature = "fdeflate" +))] +pub use self::fdeflate::*; + // If no backend is enabled, fail fast with a clear error message. #[cfg(not(feature = "any_impl"))] compile_error!("No compression backend selected; enable one of `zlib`, `zlib-ng`, `zlib-rs`, or the default `rust_backend` feature."); diff --git a/src/mem.rs b/src/mem.rs index 9ac5532d..085f6b01 100644 --- a/src/mem.rs +++ b/src/mem.rs @@ -113,6 +113,7 @@ pub enum FlushDecompress { /// The inner state for an error when decompressing #[derive(Clone, Debug)] +#[allow(dead_code)] pub(crate) enum DecompressErrorInner { General { msg: ErrorMessage }, NeedsDictionary(u32), @@ -142,6 +143,7 @@ pub(crate) fn decompress_failed(msg: ErrorMessage) -> Result(adler: u32) -> Result { Err(DecompressError(DecompressErrorInner::NeedsDictionary( adler, @@ -663,6 +665,7 @@ mod tests { use crate::write; use crate::{Compression, Decompress, FlushDecompress}; + #[cfg(any(feature = "any_zlib", feature = "miniz_oxide"))] use crate::{Compress, FlushCompress}; #[test] @@ -762,6 +765,7 @@ mod tests { assert_eq!(err.message(), Some("invalid stored block lengths")); } + #[cfg(any(feature = "any_zlib", feature = "miniz_oxide"))] fn compress_with_flush(flush: FlushCompress) -> Vec { let incompressible = (0..=255).collect::>(); let mut output = vec![0; 1024]; @@ -796,6 +800,7 @@ mod tests { } #[test] + #[cfg(any(feature = "any_zlib", feature = "miniz_oxide"))] fn test_partial_flush() { let output = compress_with_flush(FlushCompress::Partial); @@ -805,6 +810,7 @@ mod tests { } #[test] + #[cfg(any(feature = "any_zlib", feature = "miniz_oxide"))] fn test_sync_flush() { let output = compress_with_flush(FlushCompress::Sync); @@ -813,6 +819,7 @@ mod tests { } #[test] + #[cfg(any(feature = "any_zlib", feature = "miniz_oxide"))] fn test_full_flush() { let output = compress_with_flush(FlushCompress::Full); assert_eq!(output.len(), 527); From d84868e8f6e71f434363b2c23ea4e760c7d470a6 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Mon, 13 Apr 2026 23:40:57 +0100 Subject: [PATCH 2/2] Eliminate secondary output buffer in fdeflate compression path Instead of buffering all compressed output in a Vec and draining it later, drain the compressor's inner writer directly after each write_data() call. This avoids unbounded memory growth during compression and reduces unnecessary copying. Uses fdeflate's new get_writer_mut() API to access the inner Vec writer and drain produced bytes incrementally into the caller's output slice. Co-Authored-By: Claude --- src/ffi/fdeflate.rs | 111 ++++++++++++++++++++++++++------------------ 1 file changed, 66 insertions(+), 45 deletions(-) diff --git a/src/ffi/fdeflate.rs b/src/ffi/fdeflate.rs index bc8a7d9e..916cece8 100644 --- a/src/ffi/fdeflate.rs +++ b/src/ffi/fdeflate.rs @@ -164,15 +164,21 @@ impl Backend for Inflate { /// Wraps fdeflate's Compressor to implement the streaming DeflateBackend interface. /// -/// fdeflate's Compressor takes a `Write` target and has `write_data`/`finish` methods. -/// We use a `Vec` as the internal output buffer. Since fdeflate writes compressed -/// data to the writer during `write_data` and `finish` calls, we buffer that output -/// and drain it into the caller's output buffer on each `compress` call. +/// fdeflate's Compressor writes compressed data to its inner `Vec` writer +/// incrementally during `write_data()` calls. After each call, we drain the +/// writer's buffer directly into the caller's output slice, avoiding any +/// secondary buffering. +/// +/// After `finish()` is called, any remaining compressed data that didn't fit +/// in the caller's output is held in `finished_buf` until drained. pub struct Deflate { - /// Buffered compressed output that hasn't been returned to the caller yet. - output_buf: Vec, /// The compressor state. Set to `None` after `finish()` is called. inner: Option<::fdeflate::Compressor>>, + /// Holds leftover compressed data after `finish()` that didn't fit in the + /// caller's output. Only populated once the compressor is consumed. + finished_buf: Vec, + /// Read position within `finished_buf`. + finished_pos: usize, total_in: u64, total_out: u64, level: u8, @@ -189,6 +195,16 @@ impl fmt::Debug for Deflate { } } +/// Drain as many bytes as possible from `src[*pos..]` into `output`, +/// returning the number of bytes copied. +fn drain_to_output(src: &[u8], pos: &mut usize, output: &mut [u8]) -> usize { + let available = src.len() - *pos; + let copy_len = available.min(output.len()); + output[..copy_len].copy_from_slice(&src[*pos..*pos + copy_len]); + *pos += copy_len; + copy_len +} + impl DeflateBackend for Deflate { fn make(level: Compression, zlib_header: bool, _window_bits: u8) -> Self { let level_u8 = level.level().min(9) as u8; @@ -196,8 +212,9 @@ impl DeflateBackend for Deflate { ::fdeflate::Compressor::new(Vec::new(), level_u8, zlib_header).unwrap(); Deflate { - output_buf: Vec::new(), inner: Some(compressor), + finished_buf: Vec::new(), + finished_pos: 0, total_in: 0, total_out: 0, level: level_u8, @@ -211,70 +228,73 @@ impl DeflateBackend for Deflate { output: &mut [u8], flush: FlushCompress, ) -> Result { - // If we have buffered output from a previous call, drain that first - // before processing new input. - if !self.output_buf.is_empty() { - let copy_len = self.output_buf.len().min(output.len()); - output[..copy_len].copy_from_slice(&self.output_buf[..copy_len]); - self.output_buf.drain(..copy_len); - self.total_out += copy_len as u64; - - if !self.output_buf.is_empty() { - // Still more buffered output to drain, don't consume any input - return Ok(Status::Ok); + // After finish(), drain any remaining compressed data. + if self.inner.is_none() { + if self.finished_pos < self.finished_buf.len() { + let n = drain_to_output(&self.finished_buf, &mut self.finished_pos, output); + self.total_out += n as u64; + if self.finished_pos < self.finished_buf.len() { + return Ok(Status::Ok); + } } + return Ok(Status::StreamEnd); + } - // If we already finished and the buffer is now drained, we're done. - if self.inner.is_none() { - return Ok(Status::StreamEnd); - } + let compressor = self.inner.as_mut().unwrap(); - // Buffer drained but no new input and not finishing - signal caller - if input.is_empty() && flush == FlushCompress::None { - return Ok(Status::Ok); + // Drain any compressed data already sitting in the writer from a + // previous write_data() call before feeding new input. + let mut out_pos = 0; + { + let writer = compressor.get_writer_mut(); + let n = drain_to_output(writer, &mut 0, &mut output[out_pos..]); + // Remove the drained bytes from the front of the writer Vec. + if n > 0 { + writer.drain(..n); } + self.total_out += n as u64; + out_pos += n; } - // If the compressor has already been finished and there's nothing - // left to drain, signal completion. - if self.inner.is_none() { - return Ok(Status::StreamEnd); - } - - // Feed input to the compressor + // Feed input to the compressor. if !input.is_empty() { - let compressor = self.inner.as_mut().unwrap(); if compressor.write_data(input).is_err() { return mem::compress_failed(ErrorMessage); } self.total_in += input.len() as u64; + + // Drain newly produced compressed data into the remaining output space. + let writer = compressor.get_writer_mut(); + let n = drain_to_output(writer, &mut 0, &mut output[out_pos..]); + if n > 0 { + writer.drain(..n); + } + self.total_out += n as u64; + out_pos += n; } if flush == FlushCompress::Finish { - // Finalize the compressor and collect all remaining output + // Finalize the compressor and collect all remaining output. let compressor = self.inner.take().unwrap(); let compressed = match compressor.finish() { Ok(c) => c, Err(_) => return mem::compress_failed(ErrorMessage), }; - let copy_len = compressed.len().min(output.len()); - output[..copy_len].copy_from_slice(&compressed[..copy_len]); - self.total_out += copy_len as u64; + let n = drain_to_output(&compressed, &mut 0, &mut output[out_pos..]); + self.total_out += n as u64; - if copy_len < compressed.len() { - self.output_buf.extend_from_slice(&compressed[copy_len..]); + if n < compressed.len() { + // Couldn't fit everything — stash the remainder. + self.finished_buf = compressed; + self.finished_pos = n; return Ok(Status::Ok); } return Ok(Status::StreamEnd); } - // For non-Finish calls: fdeflate buffers compressed data internally in - // the Vec writer. We can't extract partial output without finishing, - // so we just report that input was consumed. The compressed output will - // become available when finish() is eventually called. - if input.is_empty() { + if out_pos == 0 && input.is_empty() { Ok(Status::BufError) } else { Ok(Status::Ok) @@ -284,7 +304,8 @@ impl DeflateBackend for Deflate { fn reset(&mut self) { self.total_in = 0; self.total_out = 0; - self.output_buf.clear(); + self.finished_buf.clear(); + self.finished_pos = 0; self.inner = Some( ::fdeflate::Compressor::new(Vec::new(), self.level, self.zlib_header).unwrap(), );