Skip to content

Commit

Permalink
fix units
Browse files Browse the repository at this point in the history
  • Loading branch information
chengr4 committed Feb 24, 2024
1 parent 2338824 commit a39f00b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 23 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rfcalc"
version = "0.3.2"
version = "0.3.3"
edition = "2021"
authors = ["R4 Cheng <[email protected]>"]
license = "MIT"
Expand Down
43 changes: 22 additions & 21 deletions src/calc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"(?<num1>\d+)\s*(?<unit1>bits|bit|kb|mb|gb|tb)\s*(?<op>/)\s*(?<num2>\d+)\s*(?<unit2>bits|bit|kb|mb|gb|tb)").unwrap();
let re = Regex::new(r"(?<num1>\d+)\s*(?<unit1>byte|bytes|kb|mb|gb|tb)\s*(?<op>/)\s*(?<num2>\d+)\s*(?<unit2>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(),
};

Expand Down

0 comments on commit a39f00b

Please sign in to comment.