1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! Frontend for stomper compression tool. See [libstomper](https://docs.rs/libstomper/0.1.0/libstomper/) for implemented algorithms
//!
use libstomper::{huffman::Huffman, lzw::LZW, Compressor};
use std::error;
use std::fs::File;
use std::io::{BufReader, BufWriter, Error, ErrorKind};
use std::path::PathBuf;
use structopt::StructOpt;

/// Runs program
pub fn run(args: Args) -> Result<(), Box<dyn error::Error>> {
    let mut input = BufReader::new(File::open(args.input)?);
    // Choose where to write encoded/decoded data
    // Defaults as output.stmpd if no argrument given
    let out_filename = args.output.unwrap_or(PathBuf::from("output.stmpd"));
    let mut output = BufWriter::new(File::create(out_filename)?);

    // Chooses the type of compression based on args.compressor
    // Return error if no match is found
    match args.compressor.as_str() {
        "lzw" => match args.decompress {
            true => LZW::decode(&mut input, &mut output),
            false => LZW::encode(&mut input, &mut output),
        },
        "huffman" | "huff" => match args.decompress {
            true => Huffman::decode(&mut input, &mut output),
            false => Huffman::encode(&mut input, &mut output),
        },

        s => {
            return Err(Box::new(Error::new(
                ErrorKind::InvalidInput,
                format!("{} is not a compression type", s),
            )))
        }
    }?;
    Ok(())
}

/// Struct for command-line arguments collected with structopt crate
#[derive(StructOpt)]
pub struct Args {
    #[structopt(short, long)]
    pub decompress: bool,

    pub compressor: String,

    #[structopt(parse(from_os_str))]
    pub input: PathBuf,

    #[structopt(short, long)]
    pub output: Option<PathBuf>,
}