diff options
author | Bartek IwaĆczuk <biwanczuk@gmail.com> | 2022-12-13 02:52:10 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-12-12 20:52:10 -0500 |
commit | 8c026dab92b20fea44bc66f84db48b885c7264d1 (patch) | |
tree | 884704fb4721c9e227859451e58f524ace0a2261 /cli/util/display.rs | |
parent | 4a17c930882c5765e5fdedb50b6493469f61e32d (diff) |
feat: improve download progress bar (#16984)
Co-authored-by: David Sherret <dsherret@gmail.com>
Diffstat (limited to 'cli/util/display.rs')
-rw-r--r-- | cli/util/display.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/cli/util/display.rs b/cli/util/display.rs index f13965e28..16b301866 100644 --- a/cli/util/display.rs +++ b/cli/util/display.rs @@ -26,6 +26,25 @@ pub fn human_size(size: f64) -> String { format!("{}{}{}", negative, pretty_bytes, unit) } +const BYTES_TO_KIB: u64 = 2u64.pow(10); +const BYTES_TO_MIB: u64 = 2u64.pow(20); + +/// Gets the size used for downloading data. The total bytes is used to +/// determine the units to use. +pub fn human_download_size(byte_count: u64, total_bytes: u64) -> String { + return if total_bytes < BYTES_TO_MIB { + get_in_format(byte_count, BYTES_TO_KIB, "KiB") + } else { + get_in_format(byte_count, BYTES_TO_MIB, "MiB") + }; + + fn get_in_format(byte_count: u64, conversion: u64, suffix: &str) -> String { + let converted_value = byte_count / conversion; + let decimal = (byte_count % conversion) * 100 / conversion; + format!("{}.{:0>2}{}", converted_value, decimal, suffix) + } +} + /// A function that converts a milisecond elapsed time to a string that /// represents a human readable version of that time. pub fn human_elapsed(elapsed: u128) -> String { @@ -85,6 +104,31 @@ mod tests { } #[test] + fn test_human_download_size() { + assert_eq!( + human_download_size(BYTES_TO_KIB / 100 - 1, BYTES_TO_KIB), + "0.00KiB" + ); + assert_eq!( + human_download_size(BYTES_TO_KIB / 100 + 1, BYTES_TO_KIB), + "0.01KiB" + ); + assert_eq!( + human_download_size(BYTES_TO_KIB / 5, BYTES_TO_KIB), + "0.19KiB" + ); + assert_eq!( + human_download_size(BYTES_TO_MIB - 1, BYTES_TO_MIB - 1), + "1023.99KiB" + ); + assert_eq!(human_download_size(BYTES_TO_MIB, BYTES_TO_MIB), "1.00MiB"); + assert_eq!( + human_download_size(BYTES_TO_MIB * 9 - 1523, BYTES_TO_MIB), + "8.99MiB" + ); + } + + #[test] fn test_human_elapsed() { assert_eq!(human_elapsed(1), "1ms"); assert_eq!(human_elapsed(256), "256ms"); |