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.
Code
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::GzEncoderandflate2::Compressionare a real dependency, resolved by the package manager. - The
Resultvalues 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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.