Skip to content

Commit

Permalink
Support fractions in data amounts
Browse files Browse the repository at this point in the history
  • Loading branch information
kacperzuk-neti committed Jul 25, 2024
1 parent 6cd85d2 commit 47d35c4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 24 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion fplus-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ alloy = { git = "https://github.com/alloy-rs/alloy", version = "0.1.0", features
"eip712",
] }
tempfile = "3.10.1"
size = "0.5.0-preview2"

[dev-dependencies]
actix-rt = "2.9.0"

[features]
online-tests = []
online-tests = []
39 changes: 16 additions & 23 deletions fplus-lib/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,9 @@
use regex::Regex;
use size::Size;

pub fn parse_size_to_bytes(size: &str) -> Option<u64> {
let re = Regex::new(r"^(\d+)\s?([a-zA-Z]+)$").unwrap();
let caps = re.captures(size.trim())?;

let number = caps.get(1)?.as_str().parse::<u64>().ok()?;
let unit = caps.get(2)?.as_str().to_uppercase();

// Normalize the unit by removing any trailing 'i', 's' and converting to upper case
let normalized_unit = unit.trim_end_matches('S');

match normalized_unit {
"KIB" => Some(number * 1024), // 2^10
"MIB" => Some(number * 1024 * 1024), // 2^20
"GIB" => Some(number * 1024 * 1024 * 1024), // 2^30
"TIB" => Some(number * 1024 * 1024 * 1024 * 1024), // 2^40
"PIB" => Some(number * 1024 * 1024 * 1024 * 1024 * 1024), // 2^50
"KB" => Some(number * 1000), // 10^3
"MB" => Some(number * 1000 * 1000), // 10^6
"GB" => Some(number * 1000 * 1000 * 1000), // 10^9
"TB" => Some(number * 1000 * 1000 * 1000 * 1000), // 10^12
"PB" => Some(number * 1000 * 1000 * 1000 * 1000 * 1000), // 10^15
_ => None, // Unsupported unit
}
let size = Size::from_str(size).ok()?;
let bytes = size.bytes();
bytes.try_into().ok()
}

pub fn compare_allowance_and_allocation(
Expand Down Expand Up @@ -83,4 +64,16 @@ mod tests {
let res = parse_size_to_bytes("2PiB");
assert_eq!(res, Some(2251799813685248));
}

#[test]
fn should_work_with_fractions() {
let res = parse_size_to_bytes("4.32PiB");
assert_eq!(res, Some(4863887597560136));
}

#[test]
fn should_work_with_fractions_with_space() {
let res = parse_size_to_bytes("4.32 PiB");
assert_eq!(res, Some(4863887597560136));
}
}

0 comments on commit 47d35c4

Please sign in to comment.