Skip to content
1 change: 1 addition & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ zlib-rs = { version = "0.6.7", optional = true, default-features = false, featur
## This implementation uses only safe Rust code and doesn't require a C compiler.
## It provides good performance for most use cases while being completely portable.
miniz_oxide = { version = "0.9.0", optional = true, features = ["simd"] }
fdeflate = { git = "https://github.com/Shnatsel/fdeflate.git", branch = "flate2-api-changes", optional = true }
crc32fast = { version = "1.2.0", default-features = false, optional = true }
document-features = { version = "0.2", optional = true }

[dev-dependencies]
miniz_oxide = "0.9.0"
futures = { version = "0.3", default-features = false }
rand = "0.9"
quickcheck = { version = "1.0", default-features = false }
Expand Down Expand Up @@ -61,6 +63,9 @@ zlib-rs = ["any_zlib", "dep:zlib-rs"] # zlib-rs uses its own crc32 implementatio
## Use the pure Rust `miniz_oxide` backend.
miniz_oxide = ["any_impl", "dep:miniz_oxide", "dep:crc32fast"]

## Use the pure Rust `fdeflate` backend.
fdeflate = ["any_impl", "dep:fdeflate", "dep:crc32fast"]

## Use the system's installed zlib library.
## This is useful when you need compatibility with other C code that uses zlib,
## or when you want to use the system-provided zlib for consistency.
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ implementation at the cost of some `unsafe`, you can use `zlib-rs`:
flate2 = { version = "1.1.10", features = ["zlib-rs", "runtime_detection"], default-features = false }
```

### fdeflate backend on this branch

The `fdeflate` feature selects a safe Rust backend with bounded streaming
buffers. It currently requires `std` and Rust 1.88 or newer. Large initialized
decompression destinations can be decoded into directly; small or uninitialized
destinations use a reusable 96 KiB history/output buffer. Compression and
decompression continue across internal buffer boundaries within a single call.

### C backends

While zlib-rs is [the fastest overall](https://trifectatech.org/blog/zlib-rs-is-faster-than-c/),
Expand Down
76 changes: 76 additions & 0 deletions examples/corpus_bench.rs
Original file line number Diff line number Diff line change
@@ -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 -- <directory>`. 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]);
}
}
}
10 changes: 10 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
flate2 = { path = ".." }
miniz_oxide = "0.9.0"

[features]
fdeflate = ["flate2/fdeflate"]

# Prevent this from interfering with workspaces
[workspace]
Expand All @@ -22,3 +26,9 @@ name = "fuzz_gz_roundtrip"
path = "fuzz_targets/fuzz_gz_roundtrip.rs"
test = false
doc = false

[[bin]]
name = "streaming"
path = "fuzz_targets/streaming.rs"
test = false
doc = false
4 changes: 4 additions & 0 deletions fuzz/fuzz_targets/streaming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#![no_main]
#[path = "../streaming.rs"]
mod streaming;
libfuzzer_sys::fuzz_target!(|data: &[u8]| streaming::exercise(data));
152 changes: 152 additions & 0 deletions fuzz/streaming.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading