hru(1): adds more descriptive comments
This commit is contained in:
parent
e4e823a309
commit
a9b388fe4b
39
src/hru.rs
39
src/hru.rs
@ -29,40 +29,45 @@ extern crate sysexits;
|
||||
use strerror::StrError;
|
||||
use sysexits::{ EX_DATAERR, EX_IOERR, EX_SOFTWARE };
|
||||
|
||||
/* list of SI prefixes */
|
||||
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")
|
||||
(3, "k"), /* kilo */
|
||||
(6, "M"), /* mega */
|
||||
(9, "G"), /* giga */
|
||||
(12, "T"), /* tera */
|
||||
(15, "P"), /* peta */
|
||||
(18, "E"), /* exa */
|
||||
(21, "Z"), /* zetta */
|
||||
(24, "Y"), /* yotta */
|
||||
(27, "R"), /* ronna */
|
||||
(30, "Q"), /* quetta */
|
||||
];
|
||||
|
||||
fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> {
|
||||
|
||||
/* preserve decimal places in output by casting to a float */
|
||||
let mut out = (input as f64, (0_u32, ""));
|
||||
if input < 1000 { return Ok(out); }
|
||||
|
||||
if input < 1000 { return Ok(out); } /* too low to convert */
|
||||
|
||||
for (n, p) in LIST {
|
||||
let c = match 10_u128.checked_pow(n) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
None => { /* too big for the laws of computing :( */
|
||||
return Err(format!("10^{}: Integer overflow", n.to_string()));
|
||||
},
|
||||
};
|
||||
|
||||
match c.cmp(&input) {
|
||||
Ordering::Less => {
|
||||
Ordering::Less => { /* c < input */
|
||||
/* the program will keep assigning out every loop until either
|
||||
* the list runs out of higher prefix bases or the input is
|
||||
* greater than the prefix base */
|
||||
out = (input as f64 / c as f64, (n, p));
|
||||
},
|
||||
Ordering::Equal => {
|
||||
Ordering::Equal => { /* c == input */
|
||||
return Ok((input as f64 / c as f64, (n, p)));
|
||||
},
|
||||
Ordering::Greater => {},
|
||||
Ordering::Greater => {}, /* c > input */
|
||||
};
|
||||
}
|
||||
|
||||
@ -72,6 +77,7 @@ fn convert(input: u128) -> Result<(f64, (u32, &'static str)), String> {
|
||||
fn main() -> ExitCode {
|
||||
let argv = args().collect::<Vec<String>>();
|
||||
let mut buf = String::new();
|
||||
|
||||
while let Ok(_) = stdin().read_line(&mut buf) {
|
||||
if buf.is_empty() { return ExitCode::SUCCESS; }
|
||||
|
||||
@ -96,6 +102,7 @@ fn main() -> ExitCode {
|
||||
|
||||
let si_prefix = format!("{}B", prefix.1);
|
||||
|
||||
/* round output number to one decimal place */
|
||||
let out = ((number * 10.0).round() / 10.0).to_string();
|
||||
|
||||
stdout().write_all(format!("{} {}\n", out, si_prefix).as_bytes())
|
||||
|
Loading…
Reference in New Issue
Block a user