From a39f00b2cbf75fd7cdad0ac7385f6ec8ef8a5a48 Mon Sep 17 00:00:00 2001 From: R4 Cheng Date: Sat, 24 Feb 2024 21:43:30 +0800 Subject: [PATCH] fix units --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/calc.rs | 43 ++++++++++++++++++++++--------------------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f79f546..910039c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,7 +249,7 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "rfcalc" -version = "0.3.2" +version = "0.3.3" dependencies = [ "clap", "regex", diff --git a/Cargo.toml b/Cargo.toml index ed37cb0..613e6f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rfcalc" -version = "0.3.2" +version = "0.3.3" edition = "2021" authors = ["R4 Cheng "] license = "MIT" diff --git a/src/calc.rs b/src/calc.rs index 5b5f5ae..43e2491 100644 --- a/src/calc.rs +++ b/src/calc.rs @@ -27,48 +27,49 @@ pub fn calc_combination(n: u64, k: u64) -> u64 { numerator / denominator } +/// B: byte #[derive(PartialEq, PartialOrd)] -enum BitUnit { - Bit, +enum ByteUnit { + B, KB, MB, GB, TB, } -impl BitUnit { +impl ByteUnit { fn to_bits(&self) -> u64 { match self { - BitUnit::Bit => 1, - BitUnit::KB => 2u64.pow(10), // 2^10 - BitUnit::MB => 2u64.pow(20), // 2^20 - BitUnit::GB => 2u64.pow(30), // 2^30 - BitUnit::TB => 2u64.pow(40), // 2^40 + ByteUnit::B => 1, + ByteUnit::KB => 2u64.pow(10), // 2^10 + ByteUnit::MB => 2u64.pow(20), // 2^20 + ByteUnit::GB => 2u64.pow(30), // 2^30 + ByteUnit::TB => 2u64.pow(40), // 2^40 } } } pub fn devide_bytes(expression: &str) -> String { - let re = Regex::new(r"(?\d+)\s*(?bits|bit|kb|mb|gb|tb)\s*(?/)\s*(?\d+)\s*(?bits|bit|kb|mb|gb|tb)").unwrap(); + let re = Regex::new(r"(?\d+)\s*(?byte|bytes|kb|mb|gb|tb)\s*(?/)\s*(?\d+)\s*(?byte|bytes|kb|mb|gb|tb)").unwrap(); if let Some(caps) = re.captures(expression) { let num1: u64 = caps.name("num1").unwrap().as_str().parse().unwrap(); let unit1 = match caps.name("unit1").unwrap().as_str() { - "bits" => BitUnit::Bit, - "bit" => BitUnit::Bit, - "kb" => BitUnit::KB, - "mb" => BitUnit::MB, - "gb" => BitUnit::GB, - "tb" => BitUnit::TB, + "byte" => ByteUnit::B, + "bytes" => ByteUnit::B, + "kb" => ByteUnit::KB, + "mb" => ByteUnit::MB, + "gb" => ByteUnit::GB, + "tb" => ByteUnit::TB, _ => return "Wrong input".to_string(), }; let num2: u64 = caps.name("num2").unwrap().as_str().parse().unwrap(); let unit2 = match caps.name("unit2").unwrap().as_str() { - "bits" => BitUnit::Bit, - "bit" => BitUnit::Bit, - "kb" => BitUnit::KB, - "mb" => BitUnit::MB, - "gb" => BitUnit::GB, - "tb" => BitUnit::TB, + "byte" => ByteUnit::B, + "bytes" => ByteUnit::B, + "kb" => ByteUnit::KB, + "mb" => ByteUnit::MB, + "gb" => ByteUnit::GB, + "tb" => ByteUnit::TB, _ => return "Wrong input".to_string(), };