Use humansize for file size formatting

syntax_id
Wilfred Hughes 2023-08-12 22:34:11 +07:00
parent d901ac6e9e
commit 3c702d0490
3 changed files with 22 additions and 31 deletions

16
Cargo.lock generated

@ -244,6 +244,7 @@ dependencies = [
"crossterm",
"glob",
"hashbrown 0.12.3",
"humansize",
"itertools",
"lazy_static",
"libc",
@ -362,6 +363,15 @@ dependencies = [
"libc",
]
[[package]]
name = "humansize"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7"
dependencies = [
"libm",
]
[[package]]
name = "humantime"
version = "1.3.0"
@ -402,6 +412,12 @@ version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
[[package]]
name = "libm"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4"
[[package]]
name = "libmimalloc-sys"
version = "0.1.24"

@ -63,6 +63,7 @@ glob = "0.3.1"
strum = { version = "0.25", features = ["derive"] }
# hashbrown 0.13 requires rust 1.61
hashbrown = "0.12.3"
humansize = "2.1.3"
[dev-dependencies]
# assert_cmd 2.0.6 requires rust 1.60

@ -62,6 +62,7 @@ use parse::guess_language::{guess, language_name, Language, LanguageOverride};
static GLOBAL: MiMalloc = MiMalloc;
use diff::sliders::fix_all_sliders;
use humansize::{format_size, BINARY};
use options::{DiffOptions, DisplayMode, DisplayOptions, FileArgument, Mode};
use owo_colors::OwoColorize;
use rayon::prelude::*;
@ -263,21 +264,6 @@ fn main() {
};
}
fn format_num_bytes(num_bytes: usize) -> String {
if num_bytes >= 1024 * 1024 * 1024 {
let g = num_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
return format!("{}GiB", g.round());
} else if num_bytes >= 1024 * 1024 {
let m = num_bytes as f64 / (1024.0 * 1024.0);
return format!("{}MiB", m.round());
} else if num_bytes >= 1024 {
let k = num_bytes as f64 / 1024.0;
return format!("{}KiB", k.round());
}
format!("{}B", num_bytes)
}
/// Print a diff between two files.
fn diff_file(
display_path: &str,
@ -526,7 +512,10 @@ fn diff_file_content(
}
Err(tsp::ExceededByteLimit(num_bytes)) => {
let file_format = FileFormat::TextFallback {
reason: format!("{} exceeded DFT_BYTE_LIMIT", &format_num_bytes(num_bytes)),
reason: format!(
"{} exceeded DFT_BYTE_LIMIT",
&format_size(num_bytes, BINARY)
),
};
if diff_options.check_only {
@ -765,19 +754,4 @@ mod tests {
assert_eq!(res.lhs_positions, vec![]);
assert_eq!(res.rhs_positions, vec![]);
}
#[test]
fn test_num_bytes_small() {
assert_eq!(&format_num_bytes(200), "200B");
}
#[test]
fn test_num_bytes_kb() {
assert_eq!(&format_num_bytes(10_000), "10KiB");
}
#[test]
fn test_num_bytes_mb() {
assert_eq!(&format_num_bytes(3_000_000), "3MiB");
}
}