hru(1): fixed overflow

This commit is contained in:
Emma Tebibyte 2024-02-13 23:56:01 -07:00
parent d0205b71da
commit 1299aefc39
Signed by untrusted user: emma
GPG Key ID: 06FA419A1698C270

View File

@ -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",