Gzip Compress and Decompress Bytes

Compress an in-memory payload with flate2's GzEncoder, decompress it through GzDecoder, and verify the round trip byte for byte.

RustData Integrity

Code

snippet
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use std::io::{self, Read, Write};

fn compress(input: &[u8]) -> io::Result<Vec<u8>> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
    encoder.write_all(input)?;
    encoder.finish()
}

fn decompress(input: &[u8]) -> io::Result<Vec<u8>> {
    let mut decoder = GzDecoder::new(input);
    let mut output = Vec::new();
    decoder.read_to_end(&mut output)?;
    Ok(output)
}

fn main() -> io::Result<()> {
    let payload = b"hello gzip ".repeat(64);
    let compressed = compress(&payload)?;
    let restored = decompress(&compressed)?;
    println!(
        "{} -> {} bytes, identical={}",
        payload.len(),
        compressed.len(),
        restored == payload
    );
    Ok(())
}