Browse Source

Added extension aware compression/decompression

AvariceLHubris 1 month ago
parent
commit
054d09beef
2 changed files with 31 additions and 8 deletions
  1. 10 7
      src/cli.rs
  2. 21 1
      src/main.rs

+ 10 - 7
src/cli.rs

@@ -4,19 +4,22 @@ use clap::Parser;
 use clap::ValueEnum;
 
 #[derive(Parser, Debug)]
-#[command(version, about, long_about= "A compression utility for utf-8 encoded text, \
-    using only basic canonical huffman encoding.")]
+#[command(
+    version,
+    about,
+    long_about = "A compression utility for utf-8 encoded text, \
+    using only basic canonical huffman encoding."
+)]
 pub struct Args {
-
-    /// input file
+    /// The input file to be (de)compressed.
     pub input_file: PathBuf,
 
-    /// output file
+    /// The optional output file for the resulting (de)compressed output.
     pub output_file: Option<PathBuf>,
 
     /// Whether to compress or extract.
-    #[arg(short, value_enum, default_value = Mode::C)]
-    pub mode: Mode,
+    #[arg(short, value_enum)]
+    pub mode: Option<Mode>,
 }
 
 #[derive(Clone, Copy, Debug, ValueEnum, Default)]

+ 21 - 1
src/main.rs

@@ -1,4 +1,5 @@
-use std::io::Write;
+use std::path::Path;
+use std::{io::Write, path::PathBuf};
 
 use anyhow::{Context, anyhow};
 use clap::Parser;
@@ -15,6 +16,11 @@ fn main() -> Result<(), anyhow::Error> {
         return Err(anyhow!("Input file did not exist."));
     }
 
+    let mode = match mode {
+        Some(mode) => mode,
+        None => determine_mode(&inputf, outputf.as_ref()),
+    };
+
     let outputf = match outputf {
         Some(name) => name,
         None => match mode {
@@ -80,6 +86,7 @@ fn main() -> Result<(), anyhow::Error> {
             let inputf =
                 std::fs::read_to_string(inputf).context("Could not read input file to string.")?;
             println!("Read: {} bytes.", in_size);
+            println!("Encoding text...");
             let char_f = huffman::hufftree::base::get_char_frequencies(&inputf);
 
             let base_tree = huffman::hufftree::base::Hufftree::new(char_f);
@@ -87,6 +94,7 @@ fn main() -> Result<(), anyhow::Error> {
 
             storage::store_tree_and_text(canonical_tree, &mut outputf, &inputf)
                 .expect("Could not store the tree and text.");
+            println!("Encoded!");
             let out_size = outputf
                 .metadata()
                 .context("Could not get the input file's metadata")?
@@ -101,3 +109,15 @@ fn main() -> Result<(), anyhow::Error> {
 
     Ok(())
 }
+
+fn determine_mode(inputf: &Path, _outputf: Option<&PathBuf>) -> cli::Mode {
+    // If '.z' at end of inputf -> Decompress.
+    if let Some(extension) = inputf.extension()
+        && extension.eq("z")
+    {
+        cli::Mode::X
+    } else {
+        // Otherwise compress
+        cli::Mode::C
+    }
+}