From fd1f06e4dd9bc73a8e22bc6db2ccb6085ab62ad4 Mon Sep 17 00:00:00 2001 From: Jacob Heider Date: Thu, 9 Jan 2025 17:11:37 -0500 Subject: [PATCH 1/2] use math to reduce clarity --- cli/src/main.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index dd239db..1ecf9d3 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -328,11 +328,5 @@ fn pretty_size(n: u64) -> (String, u64) { } fn precision(n: f64) -> usize { - if n < 10.0 { - 2 - } else if n < 100.0 { - 1 - } else { - 0 - } + 2 - (n.log10().clamp(0.0, 2.0) as usize) } From f13d5029b22221ed9595f572464995dca526e99c Mon Sep 17 00:00:00 2001 From: Jacob Heider Date: Thu, 9 Jan 2025 17:34:44 -0500 Subject: [PATCH 2/2] one more --- cli/src/main.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 1ecf9d3..f3b32ab 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -310,23 +310,27 @@ fn configure_bar(pb: &ProgressBar) { fn pretty_size(n: u64) -> (String, u64) { let units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; - let mut size = n as f64; - let mut i = 0; - let mut divisor = 1; - - while size >= 1000.0 && i < units.len() - 1 { - size /= 1024.0; - i += 1; - divisor *= 1024; - } - - let precision = if i == 0 { 0 } else { precision(size) }; - let formatted = format!("{:.precision$} {}", size, units[i], precision = precision); + // number of 1024s + let thousands = n.max(1).ilog(1024).clamp(0, units.len() as u32 - 1) as usize; + // size in the appropriate unit + let size = n as f64 / 1024.0f64.powi(thousands as i32); + // the divisor to get back to bytes + let divisor = 1024u64.pow(thousands as u32); + // number of decimal places to show (0 if we're bytes. no fractional bytes. come on.) + let precision = if thousands == 0 { 0 } else { precision(size) }; + + let formatted = format!( + "{:.precision$} {}", + size, + units[thousands], + precision = precision + ); (formatted, divisor) } fn precision(n: f64) -> usize { + // 1 > 1.00, 10 > 10.0, 100 > 100 2 - (n.log10().clamp(0.0, 2.0) as usize) }