forked from bonsai/harakit
hru(1): fixed overflow
This commit is contained in:
parent
d0205b71da
commit
1299aefc39
28
src/hru.rs
28
src/hru.rs
@ -25,28 +25,34 @@ use std::{
|
||||
|
||||
extern crate sysexits;
|
||||
|
||||
use sysexits::EX_DATAERR;
|
||||
use sysexits::{ EX_DATAERR, EX_SOFTWARE };
|
||||
|
||||
fn convert(input: u64) -> (f64, u32) {
|
||||
fn convert(input: u128) -> Result<(f64, u32), String> {
|
||||
let list: Vec<u32> = vec![3, 6, 9, 12, 15, 18, 21, 24, 27, 30];
|
||||
let mut out = (0.0, 0_u32);
|
||||
|
||||
if input < 1000 { return (input as f64, 0); }
|
||||
if input < 1000 { return Ok((input as f64, 0)); }
|
||||
|
||||
for n in list {
|
||||
let c = 10_u64.pow(n);
|
||||
let c = match 10_u128.checked_pow(n) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return Err(format!("10^{}: Integer overflow.", n.to_string()));
|
||||
},
|
||||
};
|
||||
|
||||
match c.cmp(&input) {
|
||||
Ordering::Less => {
|
||||
out = (input as f64 / c as f64, n);
|
||||
},
|
||||
Ordering::Equal => {
|
||||
return (input as f64 / c as f64, n);
|
||||
return Ok((input as f64 / c as f64, n));
|
||||
},
|
||||
Ordering::Greater => {},
|
||||
};
|
||||
}
|
||||
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
@ -55,7 +61,7 @@ fn main() -> ExitCode {
|
||||
while let Ok(_) = stdin().read_line(&mut buf) {
|
||||
if buf.is_empty() { return ExitCode::SUCCESS; }
|
||||
|
||||
let n: u64 = match buf.trim().parse() {
|
||||
let n: u128 = match buf.trim().parse() {
|
||||
Ok(f) => {
|
||||
buf.clear();
|
||||
f
|
||||
@ -66,7 +72,13 @@ fn main() -> ExitCode {
|
||||
},
|
||||
};
|
||||
|
||||
let (number, prefix) = convert(n);
|
||||
let (number, prefix) = match convert(n) {
|
||||
Ok(x) => x,
|
||||
Err(err) => {
|
||||
eprintln!("{}: {}", argv[0], err);
|
||||
return ExitCode::from(EX_SOFTWARE as u8);
|
||||
},
|
||||
};
|
||||
|
||||
let si_prefix = format!("{}B", match prefix {
|
||||
3 => "K",
|
||||
|
Loading…
Reference in New Issue
Block a user