From a168030929a3c80c769eabe9003676df731725d9 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Sun, 26 Jul 2020 09:55:03 +0200 Subject: [PATCH] Initial commit. --- .gitignore | 2 ++ Cargo.toml | 11 +++++++++++ src/lib.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..7194b92 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "io-decompress" +version = "0.1.0" +authors = ["Anders Olsson "] +edition = "2018" + +[dependencies] +bzip2 = "0.4" +flate2 = "1.0" +mime = "0.3" +mime_guess = "2.0" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5bcb1cb --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,35 @@ +use std::fs::File; +use std::io::Read; +use std::path::Path; + +use bzip2::read::BzDecoder; +use flate2::read::GzDecoder; + +pub enum Reader { + Raw(File), + Gz(GzDecoder), + Bz(BzDecoder), +} + +impl Read for Reader { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + match self { + Reader::Raw(file) => file.read(buf), + Reader::Gz(file) => file.read(buf), + Reader::Bz(file) => file.read(buf), + } + } +} + +pub fn open

(path: P) -> Result +where + P: AsRef, +{ + let file = File::open(&path)?; + + Ok(match mime_guess::from_path(path).first_raw() { + Some("application/x-gzip") => Reader::Gz(GzDecoder::new(file)), + Some("application/x-bzip2") => Reader::Bz(BzDecoder::new(file)), + _ => Reader::Raw(file), + }) +}