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

rustsnippet
31 lines
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(())
}

What the code does

Count the functions compress, decompress and main as the entire surface area of Gzip Compress and Decompress Bytes.

Result turns the error into data — visible in the type, handled by the caller.

What to watch for

  • Plan for an install step: flate2::read::GzDecoder, flate2::write::GzEncoder and flate2::Compression are a real dependency, resolved by the package manager.
  • The Result values will not let errors pass silently; each must be matched, unwrapped, or propagated.

Applying it

The main signature reads fn compress(input: &[u8]) -> io::Result<Vec<u8>>

main is the driver: it invokes compress and decompress before returning.

Statements that matter

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 compress(input: &[u8]) -> io::Result<Vec<u8>> {
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
encoder.write_all(input)?;
encoder.finish()
}
let restored = decompress(&compressed)?;

Interactive Tools for This Topic

FAQ

Is there exception handling?
No panics — `Result` values carry the failure, and `?` forwards them to the caller.
Are there third-party dependencies?
`flate2::read::GzDecoder`, `flate2::write::GzEncoder` and `flate2::Compression` — install them with the package manager before running.