Backend Development 6 min read

Build a Fast Rust Gzip Compressor: Step‑by‑Step Tutorial

This tutorial walks you through creating a simple yet efficient Gzip compression tool in Rust, covering project setup, dependency configuration, full source code, command‑line parsing with clap, file handling, compression using flate2, performance measurement, and execution instructions.

Architecture Development Notes
Architecture Development Notes
Architecture Development Notes
Build a Fast Rust Gzip Compressor: Step‑by‑Step Tutorial

In this tutorial we build a simple and efficient Gzip compression tool using Rust, covering project setup, dependencies, full source code, command‑line argument parsing with clap, file handling, compression with flate2, performance measurement, and how to run the program.

Step 1: Set up the Rust project

Create a new Cargo project and add required dependencies in Cargo.toml :

<code>cargo new rust-gzip
cd rust-gzip</code>
<code>[dependencies]
clap = { version = "4.0", features = ["derive"] }
flate2 = "1.0"
</code>

Step 2: Write the Gzip compression tool

The complete source code is:

<code>use clap::{Arg, Command};
use flate2::write::GzEncoder;
use flate2::Compression;
use std::fs::File;
use std::io::{copy, BufReader};
use std::time::Instant;

fn main() {
    // Define and parse command‑line arguments
    let matches = Command::new("Rust Gzip")
        .version("1.0")
        .author("Author Name <[email protected]>")
        .about("Gzip compression tool")
        .arg(
            Arg::new("source")
                .help("sets the input file to use")
                .required(true)
                .index(1),
        )
        .arg(
            Arg::new("target")
                .help("sets the output file to use, recommended with `.gz` extension")
                .required(true)
                .index(2),
        )
        .get_matches();

    // Get source and target values
    let source = matches.get_one::<String>("source").unwrap();
    let target = matches.get_one::<String>("target").unwrap();

    // Open source file for reading
    let input = File::open(source).expect("Failed to open file");
    let mut input = BufReader::new(input);

    // Create target file for writing
    let output = File::create(target).expect("Failed to create file");

    // Create GzEncoder to compress data
    let mut encoder = GzEncoder::new(output, Compression::default());

    // Measure compression time
    let start = Instant::now();

    // Copy data from source to encoder (compression)
    copy(&mut input, &mut encoder).expect("Failed to compress file");

    // Ensure all data is written and close the stream
    encoder.finish().expect("Failed to finish compression");

    // Print elapsed time
    println!("Compression took: {:?}", start.elapsed());

    // Print original file size
    println!(
        "Original file size: {}",
        input.get_ref().metadata().unwrap().len()
    );
}
</code>

Step 3: Code walkthrough

1. Parse command‑line arguments with clap

Two arguments are defined:

source : input file to compress.

target : output file for compressed data (usually with .gz extension).

Example usage:

<code>cargo run -- input.txt output.txt.gz</code>

2. File handling with std::fs

Use File::open to read the source file.

Use File::create to create the output file.

3. Compression with flate2

GzEncoder wraps the output file and applies Gzip compression.

Compression level can be customized with Compression::fast , Compression::best , or Compression::default .

4. Performance measurement

Use std::time::Instant to measure how long the compression takes.

5. Error handling

The program provides clear error messages for file I/O or compression failures.

Step 4: Run the program

Create a sample text file (e.g., input.txt ) and execute:

<code>cargo run -- input.txt output.gz</code>

Typical output:

<code>Compression took: 22.315ms
Original file size: 1048576</code>

Conclusion

This tutorial demonstrates how to build a practical Gzip compression tool in Rust, showcasing essential Rust programming techniques that can be extended or integrated into larger projects.

performanceCLIRustgzipcompression
Architecture Development Notes
Written by

Architecture Development Notes

Focused on architecture design, technology trend analysis, and practical development experience sharing.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.