From 63cf71641ae51085ad76977d3adf7ad81b263872 Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Sun, 5 Feb 2023 17:28:39 -0800 Subject: [PATCH] Display file size in the header if it's too big --- CHANGELOG.md | 5 +++++ src/main.rs | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c014b8ec..7cd229f8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ ## 0.44 (unreleased) +### Display + +If a file exceeds DFT_BYTE_LIMIT, difftastic now displays its size in +the header. + ## 0.43.1 (released 3rd February 2023) This release has no logic changes from 0.43. diff --git a/src/main.rs b/src/main.rs index 59603a260..c49e9f856 100644 --- a/src/main.rs +++ b/src/main.rs @@ -259,6 +259,21 @@ 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( lhs_display_path: &str, @@ -356,10 +371,15 @@ fn diff_file_content( _ if lhs_bytes.len() > diff_options.byte_limit || rhs_bytes.len() > diff_options.byte_limit => { + let num_bytes = std::cmp::max(lhs_bytes.len(), rhs_bytes.len()); + let lhs_positions = line_parser::change_positions(&lhs_src, &rhs_src); let rhs_positions = line_parser::change_positions(&rhs_src, &lhs_src); ( - Some("Text (exceeded DFT_BYTE_LIMIT)".into()), + Some(format!( + "Text ({} exceeded DFT_BYTE_LIMIT)", + &format_num_bytes(num_bytes), + )), lhs_positions, rhs_positions, ) @@ -711,4 +731,19 @@ 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"); + } }