Unzip a file that was embedded in the Rust application

tar zip unzip gzip flate2 include_bytes

The rocket-starter crate includes several sets of files, each one is a skeleton to start writing a Rocket-based web application in Rust.

In another article we saw how to extract the content of a tar.gz file on the disk and it turns out the code is almost exactly the same in this case as well.

The difference is that we use the bufread::GzDecoder instead of the read::GzDecoder

There is a file called example.tar.gz in the root of the crate.

In order to embed that tar.gz file in the executable binary we use the include_bytes! macro.

let zipped = include_bytes!("../example.tar.gz");

We use the flate2 to uncompress the stored bytes and the the tar crate to separate it into individual files.

Dependencies

examples/unzip-from-memory/Cargo.toml

[package]
name = "unzip-file"
version = "0.1.0"
edition = "2021"

[dependencies]
flate2 = "1.0.30"
tar = "0.4.40"

Full example unzipping a file to the disk

examples/unzip-from-memory/src/main.rs

use std::{error::Error, fs::create_dir_all, path::PathBuf};

use flate2::bufread::GzDecoder;
use tar::Archive;

fn main() {
    let folder = PathBuf::from("data");
    let zipped = include_bytes!("../example.tar.gz");

    if !folder.exists() {
        create_dir_all(&folder).unwrap()
    }

    unzip(zipped, folder).unwrap();
}

fn unzip(tar_gz: &[u8], folder: PathBuf) -> Result<(), Box<dyn Error>> {
    println!("Unzipping to {folder:?}");

    let tar = GzDecoder::new(tar_gz);
    let mut archive = Archive::new(tar);
    archive.unpack(folder)?;

    Ok(())
}

Related Pages

Unzip a file to the disk using Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo