From e3a00691801aedccc36638fb207ab984576f022c Mon Sep 17 00:00:00 2001 From: emma Date: Wed, 14 Feb 2024 00:07:06 -0700 Subject: [PATCH] hru(1): improved SI prefix logic --- src/hru.rs | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/hru.rs b/src/hru.rs index 2eae2ed..65b61f6 100644 --- a/src/hru.rs +++ b/src/hru.rs @@ -27,13 +27,25 @@ extern crate sysexits; use sysexits::{ EX_DATAERR, EX_SOFTWARE }; -fn convert(input: u128) -> Result<(f64, u32), String> { - let list: Vec = vec![3, 6, 9, 12, 15, 18, 21, 24, 27, 30]; - let mut out = (0.0, 0_u32); +const LIST: [(u32, &str); 10] = [ + (3, "K"), + (6, "M"), + (9, "G"), + (12, "T"), + (15, "P"), + (18, "E"), + (21, "Z"), + (24, "Y"), + (27, "R"), + (30, "Q") +]; - if input < 1000 { return Ok((input as f64, 0)); } +fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> { - for n in list { + let mut out = (input as f64, (0_u32, "")); + if input < 1000 { return Ok(out); } + + for (n, p) in LIST { let c = match 10_u128.checked_pow(n) { Some(c) => c, None => { @@ -43,10 +55,10 @@ fn convert(input: u128) -> Result<(f64, u32), String> { match c.cmp(&input) { Ordering::Less => { - out = (input as f64 / c as f64, n); + out = (input as f64 / c as f64, (n, p)); }, Ordering::Equal => { - return Ok((input as f64 / c as f64, n)); + return Ok((input as f64 / c as f64, (n, p))); }, Ordering::Greater => {}, }; @@ -80,19 +92,7 @@ fn main() -> ExitCode { }, }; - let si_prefix = format!("{}B", match prefix { - 3 => "K", - 6 => "M", - 9 => "G", - 12 => "T", - 15 => "P", - 18 => "E", - 21 => "Z", - 24 => "Y", - 27 => "R", - 30 => "Q", - _ => "", - }); + let si_prefix = format!("{}B", prefix.1); let out = ((number * 10.0).round() / 10.0).to_string();