From 1299aefc39a73cc7110545e489461d8740285afe Mon Sep 17 00:00:00 2001 From: emma Date: Tue, 13 Feb 2024 23:56:01 -0700 Subject: [PATCH] hru(1): fixed overflow --- src/hru.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/hru.rs b/src/hru.rs index 1e57be4..2eae2ed 100644 --- a/src/hru.rs +++ b/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 = 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",