Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion crates/uv-console/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ license = { workspace = true }

[lib]
doctest = false
test = false

[lints]
workspace = true
Expand Down
81 changes: 67 additions & 14 deletions crates/uv-console/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use console::{Key, Term, measure_text_width, style};
use std::{cmp::Ordering, iter};
use std::{cmp::Ordering, fmt, iter};

/// Prompt the user for confirmation in the given [`Term`].
///
Expand Down Expand Up @@ -297,18 +297,71 @@ pub fn input(prompt: &str, term: &Term) -> std::io::Result<String> {
Ok(input)
}

/// Formats a number of bytes into a human readable SI-prefixed size (binary units).
///
/// Returns a tuple of `(quantity, units)`.
#[allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_precision_loss,
clippy::cast_sign_loss
)]
pub fn human_readable_bytes(bytes: u64) -> (f32, &'static str) {
/// Formats a number of bytes into a human readable IEC-prefixed size (binary units).
#[expect(clippy::cast_precision_loss)]
pub fn human_readable_bytes(bytes: u64) -> impl fmt::Display {
const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
let bytes_f32 = bytes as f32;
let i = ((bytes_f32.log2() / 10.0) as usize).min(UNITS.len() - 1);
(bytes_f32 / 1024_f32.powi(i as i32), UNITS[i])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh we're doing 1024 instead of proper powers of 10 :/

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well we are specifying KiB, MiB, GiB etc. not kB, MB, GB...

I agree that 1024 based units are a convention strongly tied to technical details that users would find irrelevant, but it's also the industry standard practice at this point.


fmt::from_fn(move |formatter| {
let rounding_margin = formatter
.precision()
.and_then(|precision| i32::try_from(precision).ok())
.map_or(0.0, |precision| 0.5 / 10_f64.powi(precision));
let mut quantity = bytes as f64;
let [mut unit, units @ ..] = UNITS;

for next_unit in units {
Comment on lines +311 to +313

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a neat trick

if 1024.0 - quantity > rounding_margin {
break;
}
quantity /= 1024.0;
unit = next_unit;
}

fmt::Display::fmt(&quantity, formatter)?;
formatter.write_str(unit)
})
}

#[cfg(test)]
mod tests {
use super::human_readable_bytes;

#[test]
fn human_readable_sizes() {
const MIB: u64 = 1024_u64.pow(2);
const PIB: u64 = 1024_u64.pow(5);

assert_eq!(format!("{}", human_readable_bytes(0)), "0B");
assert_eq!(format!("{}", human_readable_bytes(1024)), "1KiB");
assert_eq!(format!("{}", human_readable_bytes(1536)), "1.5KiB");
assert_eq!(format!("{}", human_readable_bytes(u64::MAX)), "16EiB");
assert_eq!(
format!("{}", human_readable_bytes(MIB - 51)),
"1023.9501953125KiB"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one doesn't look good, the exact precision looks misplaced, a user would be satisfied with 1024KiB

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The format doesn't specify a precision so it falls back to normal float formatting.

I thought about it and I felt it was the least surprising behaviour given it's consistent with how floats are normally formatted and all the cases where we use this do specify a precision.

In this case, with {.1} it would have printed "1.0MiB".

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My confusion here may be that the function is called human_readable_bytes, but doesn't return a human-readable string, but a greek prefix to format myself.

);

assert_eq!(format!("{:.2}", human_readable_bytes(1023)), "1023.00B");
assert_eq!(format!("{:.0}", human_readable_bytes(MIB - 513)), "1023KiB");
assert_eq!(format!("{:.0}", human_readable_bytes(MIB - 512)), "1MiB");
assert_eq!(
format!("{:.1}", human_readable_bytes(MIB - 52)),
"1023.9KiB"
);
assert_eq!(format!("{:.1}", human_readable_bytes(MIB - 51)), "1.0MiB");
assert_eq!(
format!("{:.2}", human_readable_bytes(MIB - 51)),
"1023.95KiB"
);

assert_eq!(
format!("{:.10}", human_readable_bytes(PIB - 55)),
"1023.9999999999TiB"
);
// Specifically trigger a floating point imprecision corner case.
assert_eq!(
format!("{:.1}", human_readable_bytes(PIB * 1024 - PIB / 20 - 1)),
"1.0EiB"
);
}
}
4 changes: 2 additions & 2 deletions crates/uv-resolver/src/lock/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -558,9 +558,9 @@ impl<'env> TreeDisplay<'env> {
// Keep it simple: use the first wheel entry that includes a size.
if self.show_sizes {
if let Some(size_bytes) = package.wheels.iter().find_map(|wheel| wheel.size) {
let (bytes, unit) = human_readable_bytes(size_bytes);
let bytes = human_readable_bytes(size_bytes);
line.push(' ');
line.push_str(format!("{}", format!("({bytes:.1}{unit})").dimmed()).as_str());
line.push_str(format!("{}", format!("({bytes:.1})").dimmed()).as_str());
}
}

Expand Down
3 changes: 1 addition & 2 deletions crates/uv/src/commands/cache_clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ pub(crate) async fn cache_clean(
let bytes = if reported_bytes < 1024 {
format!("{reported_bytes}B")
} else {
let (bytes, unit) = human_readable_bytes(reported_bytes);
format!("{bytes:.1}{unit}")
format!("{:.1}", human_readable_bytes(reported_bytes))
};
if summary.physical_bytes_incomplete {
write!(printer.stderr(), " (at least {})", bytes.green())?;
Expand Down
3 changes: 1 addition & 2 deletions crates/uv/src/commands/cache_prune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ pub(crate) async fn cache_prune(
let bytes = if reported_bytes < 1024 {
format!("{reported_bytes}B")
} else {
let (bytes, unit) = human_readable_bytes(reported_bytes);
format!("{bytes:.1}{unit}")
format!("{:.1}", human_readable_bytes(reported_bytes))
};
if summary.physical_bytes_incomplete {
write!(printer.stderr(), " (at least {})", bytes.green())?;
Expand Down
4 changes: 2 additions & 2 deletions crates/uv/src/commands/cache_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ pub(crate) fn cache_size(
let total_bytes = disk_usage.count_ignoring_errors();

if human_readable {
let (bytes, unit) = human_readable_bytes(total_bytes);
writeln!(printer.stdout_important(), "{bytes:.1}{unit}")?;
let bytes = human_readable_bytes(total_bytes);
writeln!(printer.stdout_important(), "{bytes:.1}")?;
} else {
writeln!(printer.stdout_important(), "{total_bytes}")?;
}
Expand Down
9 changes: 4 additions & 5 deletions crates/uv/src/commands/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,23 +251,22 @@ pub(crate) async fn publish(
}
}

let size = fs_err::metadata(&group.file)?.len();
let (bytes, unit) = human_readable_bytes(size);
let bytes = human_readable_bytes(fs_err::metadata(&group.file)?.len());
if dry_run {
writeln!(
printer.stderr(),
"{} {} {}",
"Checking".bold().cyan(),
group.filename,
format!("({bytes:.1}{unit})").dimmed()
format!("({bytes:.1})").dimmed()
)?;
} else {
writeln!(
printer.stderr(),
"{} {} {}",
"Hashing".bold().green(),
group.filename,
format!("({bytes:.1}{unit})").dimmed()
format!("({bytes:.1})").dimmed()
)?;
}

Expand Down Expand Up @@ -297,7 +296,7 @@ pub(crate) async fn publish(
"{} {} {}",
"Uploading".bold().green(),
group.filename,
format!("({bytes:.1}{unit})").dimmed()
format!("({bytes:.1})").dimmed()
)?;

let uploaded = if direct {
Expand Down
3 changes: 1 addition & 2 deletions crates/uv/src/commands/reporters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,12 @@ impl ProgressReporter {
// If the file is larger than 1MB, show a message to indicate that this may take
// a while keeping the log concise.
if multi_progress.is_hidden() && !*HAS_UV_TEST_NO_CLI_PROGRESS && size > 1024 * 1024 {
let (bytes, unit) = human_readable_bytes(size);
let _ = writeln!(
self.printer.stderr(),
"{} {} {}",
direction.as_str().bold().cyan(),
name,
format!("({bytes:.1}{unit})").dimmed()
format!("({:.1})", human_readable_bytes(size)).dimmed()
);
}
progress.set_message(name);
Expand Down
Loading