diff --git a/Cargo.lock b/Cargo.lock index 4874d824..bcae383f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -301,13 +301,13 @@ dependencies = [ "chrono", "codspeed-divan-compat", "ctor", - "diff", "itoa", "pretty_assertions", "rand", "regex", "rstest", "same-file", + "ses", "tempfile", "unicode-width", "uutests", @@ -974,6 +974,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "ses" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ffac46567485eaeccaa5970d135dc1e5b4b9bb4af308d6964d4a4666cf1e96f" +dependencies = [ + "rustc-hash", +] + [[package]] name = "shlex" version = "2.0.1" diff --git a/Cargo.toml b/Cargo.toml index 5a433257..bcb9013a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,10 +18,10 @@ path = "src/main.rs" [dependencies] chrono = "0.4.38" -diff = "0.1.13" itoa = "1.0.11" regex = "1.10.4" same-file = "1.0.6" +ses = "0.0.4" unicode-width = "0.2.0" [dev-dependencies] diff --git a/benches/bench-diffutils.rs b/benches/bench-diffutils.rs index e506b3f1..f8973b51 100644 --- a/benches/bench-diffutils.rs +++ b/benches/bench-diffutils.rs @@ -81,28 +81,43 @@ mod diffutils_cmp { #[cfg(not(feature = "feat_bench_not_diff"))] mod diffutils_diff { - // use std::hint::black_box; + use std::hint::black_box; use crate::{binary, prepare::*, FILE_SIZE_KILO_BYTES}; - // use diffutilslib::params; + use diffutilslib::{normal_diff, params}; use divan::Bencher; - // bench the actual compare - // TODO diff does not have a diff function - // #[divan::bench(args = [100_000,10_000])] - // fn diff_compare_files(bencher: Bencher, bytes: u64) { - // let (from, to) = gen_testfiles(lines, 0, "id"); - // let cmd = format!("cmp {from} {to}"); - // let opts = str_to_options(&cmd).into_iter().peekable(); - // let params = params::parse_params(opts).unwrap(); - // - // bencher - // // .with_inputs(|| prepare::cmp_params_identical_testfiles(lines)) - // .with_inputs(|| params.clone()) - // .bench_refs(|params| diff::diff(¶ms).unwrap()); - // } - - // bench original GNU diff + // bench the actual diff comparison in-process on identical files + #[divan::bench(args = FILE_SIZE_KILO_BYTES)] + fn diff_compare_files_equal(bencher: Bencher, bytes: u64) { + let (from, to) = get_context().get_test_files_equal(bytes); + let from_content = std::fs::read(from).expect("Failed to read from file"); + let to_content = std::fs::read(to).expect("Failed to read to file"); + let cmd = format!("diff {from} {to}"); + let opts = str_to_options(&cmd).into_iter().peekable(); + let (params, _) = params::parse_params(opts).unwrap(); + + bencher + .with_inputs(|| (&from_content, &to_content, ¶ms)) + .bench_refs(|(from, to, params)| black_box(normal_diff(from, to, params))); + } + + // bench the actual diff comparison in-process on differing files + #[divan::bench(args = FILE_SIZE_KILO_BYTES)] + fn diff_compare_files_different(bencher: Bencher, bytes: u64) { + let (from, to) = get_context().get_test_files_different(bytes); + let from_content = std::fs::read(from).expect("Failed to read from file"); + let to_content = std::fs::read(to).expect("Failed to read to file"); + let cmd = format!("diff {from} {to}"); + let opts = str_to_options(&cmd).into_iter().peekable(); + let (params, _) = params::parse_params(opts).unwrap(); + + bencher + .with_inputs(|| (&from_content, &to_content, ¶ms)) + .bench_refs(|(from, to, params)| black_box(normal_diff(from, to, params))); + } + + // bench original GNU diff on equal files #[divan::bench(args = FILE_SIZE_KILO_BYTES)] fn cmd_diff_gnu_equal(bencher: Bencher, bytes: u64) { let (from, to) = get_context().get_test_files_equal(bytes); @@ -113,7 +128,7 @@ mod diffutils_diff { .bench_refs(|cmd_args| binary::bench_binary("diff", cmd_args)); } - // bench the compiled release version + // bench the compiled release version on equal files #[divan::bench(args = FILE_SIZE_KILO_BYTES)] fn cmd_diff_release_equal(bencher: Bencher, bytes: u64) { let (from, to) = get_context().get_test_files_equal(bytes); @@ -124,6 +139,27 @@ mod diffutils_diff { .with_inputs(|| args_str.clone()) .bench_refs(|cmd_args| binary::bench_binary("target/release/diffutils", cmd_args)); } + + // bench original GNU diff on differing files + #[divan::bench(args = FILE_SIZE_KILO_BYTES)] + fn cmd_diff_gnu_different(bencher: Bencher, bytes: u64) { + let (from, to) = get_context().get_test_files_different(bytes); + let args_str = format!("{from} {to}"); + bencher + .with_inputs(|| args_str.clone()) + .bench_refs(|cmd_args| binary::bench_binary("diff", cmd_args)); + } + + // bench the compiled release version on differing files + #[divan::bench(args = FILE_SIZE_KILO_BYTES)] + fn cmd_diff_release_different(bencher: Bencher, bytes: u64) { + let (from, to) = get_context().get_test_files_different(bytes); + let args_str = format!("diff {from} {to}"); + + bencher + .with_inputs(|| args_str.clone()) + .bench_refs(|cmd_args| binary::bench_binary("target/release/diffutils", cmd_args)); + } } mod parser { @@ -204,7 +240,6 @@ mod prepare { &self.files_equal[p] } - #[allow(unused)] pub fn get_test_files_different(&self, kb: u64) -> &(String, String) { let p = FILE_SIZE_KILO_BYTES.iter().position(|f| *f == kb).unwrap(); &self.files_different[p] @@ -358,7 +393,7 @@ mod prepare { } mod binary { - use std::process::Command; + use std::process::{Command, Stdio}; use crate::prepare::str_to_options; @@ -366,6 +401,8 @@ mod binary { let args = str_to_options(cmd_args); Command::new(program) .args(args) + .stdout(Stdio::null()) + .stderr(Stdio::null()) .status() .expect("Failed to execute binary") } diff --git a/src/context_diff.rs b/src/context_diff.rs index ddc11dd4..1a35ff60 100644 --- a/src/context_diff.rs +++ b/src/context_diff.rs @@ -129,9 +129,10 @@ fn make_diff( let mut block: Option = None; - for result in diff::slice(&expected_lines, &actual_lines) { + let differences = ses::diff_lines(&expected_lines, &actual_lines); + for result in differences.iter_changes() { match result { - diff::Result::Left(str) => { + ses::Change::Delete(str) => { if lines_since_mismatch > max_gap { results.push(mismatch); mismatch = Mismatch::new( @@ -153,7 +154,7 @@ fn make_diff( line_number_expected += 1; lines_since_mismatch = 0; } - diff::Result::Right(str) => { + ses::Change::Insert(str) => { if lines_since_mismatch > max_gap { results.push(mismatch); mismatch = Mismatch::new( @@ -175,7 +176,7 @@ fn make_diff( line_number_actual += 1; lines_since_mismatch = 0; } - diff::Result::Both(str, _) => { + ses::Change::Equal(str, _) => { // if one of them is missing a newline and the other isn't, then they don't actually match if (line_number_actual > actual_lines_count) && (line_number_expected > expected_lines_count) diff --git a/src/diff.rs b/src/diff.rs index 55fd30e5..f18293d9 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -5,7 +5,7 @@ use crate::color::{colorize, ColorWhen, Palette, PaletteError}; use crate::params::{parse_params, Format, MissingFile, Params}; -use crate::utils::report_failure_to_read_input_file; +use crate::utils::{is_identical, report_failure_to_read_input_file}; use crate::{context_diff, dir_diff, ed_diff, normal_diff, side_diff, unified_diff}; use std::env::ArgsOs; use std::ffi::OsString; @@ -132,11 +132,12 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { return Outcome::Trouble; } + if is_identical(&from_content, &to_content) { + maybe_report_identical_files(); + return Outcome::Identical; + } + if !params.text && (is_binary(&from_content) || is_binary(&to_content)) { - if from_content == to_content { - maybe_report_identical_files(); - return Outcome::Identical; - } print_files_differ( if params.brief { "Files" diff --git a/src/ed_diff.rs b/src/ed_diff.rs index 6ec73568..f258e266 100644 --- a/src/ed_diff.rs +++ b/src/ed_diff.rs @@ -71,9 +71,10 @@ fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Result { + ses::Change::Delete(str) => { if !mismatch.actual.is_empty() { results.push(mismatch); mismatch = Mismatch::new(line_number_expected, line_number_actual); @@ -81,11 +82,11 @@ fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Result { + ses::Change::Insert(str) => { mismatch.actual.push(str.to_vec()); line_number_actual += 1; } - diff::Result::Both(_str, _) => { + ses::Change::Equal(_str, _) => { line_number_expected += 1; line_number_actual += 1; if !mismatch.actual.is_empty() || !mismatch.expected.is_empty() { diff --git a/src/normal_diff.rs b/src/normal_diff.rs index f5a833f2..92370912 100644 --- a/src/normal_diff.rs +++ b/src/normal_diff.rs @@ -5,8 +5,10 @@ use std::io::Write; +use ses::Change; + use crate::params::Params; -use crate::utils::{do_write_line, line_prefix}; +use crate::utils::{do_write_line, is_identical, line_prefix}; #[derive(Debug, PartialEq)] struct Mismatch { @@ -54,9 +56,10 @@ fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Vec actual_lines.pop(); } - for result in diff::slice(&expected_lines, &actual_lines) { + let differences = ses::diff_lines(&expected_lines, &actual_lines); + for result in differences.iter_changes() { match result { - diff::Result::Left(str) => { + Change::Delete(str) => { if !mismatch.actual.is_empty() && !mismatch.actual_missing_nl { results.push(mismatch); mismatch = Mismatch::new(line_number_expected, line_number_actual); @@ -65,12 +68,12 @@ fn make_diff(expected: &[u8], actual: &[u8], stop_early: bool) -> Vec mismatch.expected_missing_nl = line_number_expected > expected_lines_count; line_number_expected += 1; } - diff::Result::Right(str) => { + Change::Insert(str) => { mismatch.actual.push(str.to_vec()); mismatch.actual_missing_nl = line_number_actual > actual_lines_count; line_number_actual += 1; } - diff::Result::Both(str, _) => { + Change::Equal(str, _) => { match ( line_number_expected > expected_lines_count, line_number_actual > actual_lines_count, @@ -121,6 +124,11 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { // See https://www.gnu.org/software/diffutils/manual/html_node/Detailed-Normal.html // for details on the syntax of the normal format. let mut output = Vec::new(); + + if is_identical(expected, actual) { + return output; + } + let diff_results = make_diff(expected, actual, params.brief); if params.brief && !diff_results.is_empty() { write!(&mut output, "\0").unwrap(); diff --git a/src/side_diff.rs b/src/side_diff.rs index faebfd19..04eb0e2a 100644 --- a/src/side_diff.rs +++ b/src/side_diff.rs @@ -4,7 +4,6 @@ // files that was distributed with this source code. use core::cmp::{max, min}; -use diff::Result; use std::{io::Write, vec}; use unicode_width::UnicodeWidthStr; @@ -350,11 +349,17 @@ pub fn diff( More studies are needed to cover GNU diff side by side with 100% accuracy, which is one of the goals of this project : ) */ - for result in diff::slice(&left_lines, &right_lines) { - match result { - Result::Left(left_ln) => push_output(left_ln, b"", b'<', output, &config).unwrap(), - Result::Right(right_ln) => push_output(b"", right_ln, b'>', output, &config).unwrap(), - Result::Both(left_ln, right_ln) => { + let differences = ses::diff_lines(&left_lines, &right_lines); + + for change in differences.iter_changes() { + match change { + ses::Change::Delete(left_ln) => { + push_output(left_ln, b"", b'<', output, &config).unwrap() + } + ses::Change::Insert(right_ln) => { + push_output(b"", right_ln, b'>', output, &config).unwrap() + } + ses::Change::Equal(left_ln, right_ln) => { push_output(left_ln, right_ln, b' ', output, &config).unwrap() } } diff --git a/src/unified_diff.rs b/src/unified_diff.rs index bd8ea43e..66b5b5e0 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -7,8 +7,10 @@ use std::collections::VecDeque; use std::io::Write; use crate::params::Params; -use crate::utils::{do_write_line, line_prefix}; -use crate::utils::{get_modification_time, write_file_header, FunctionLineFinder, TimestampStyle}; +use crate::utils::{ + do_write_line, get_modification_time, is_identical, line_prefix, write_file_header, + FunctionLineFinder, TimestampStyle, +}; #[derive(Debug, PartialEq)] pub enum DiffLine { @@ -68,9 +70,10 @@ fn make_diff( actual_lines.pop(); } - for result in diff::slice(&expected_lines, &actual_lines) { + let differences = ses::diff_lines(&expected_lines, &actual_lines); + for result in differences.iter_changes() { match result { - diff::Result::Left(str) => { + ses::Change::Delete(str) => { if lines_since_mismatch > max_gap { results.push(mismatch); mismatch = Mismatch::new( @@ -107,7 +110,7 @@ fn make_diff( line_number_expected += 1; lines_since_mismatch = 0; } - diff::Result::Right(str) => { + ses::Change::Insert(str) => { if lines_since_mismatch > max_gap { results.push(mismatch); mismatch = Mismatch::new( @@ -128,7 +131,7 @@ fn make_diff( line_number_actual += 1; lines_since_mismatch = 0; } - diff::Result::Both(str, _) => { + ses::Change::Equal(str, _) => { // if one of them is missing a newline and the other isn't, then they don't actually match if (line_number_actual > actual_lines_count) && (line_number_expected > expected_lines_count) @@ -237,6 +240,9 @@ fn make_diff( #[must_use] pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { + if is_identical(expected, actual) { + return Vec::new(); + } let from_modified_time = get_modification_time( ¶ms.from.to_string_lossy(), TimestampStyle::Iso, diff --git a/src/utils.rs b/src/utils.rs index 8bd2d18b..8590e596 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -369,6 +369,43 @@ pub fn report_failure_to_read_input_file( ); } +/// Check if two byte slices are identical with early rejection sampling. +/// +/// When files are equal, this verifies full byte equality and returns `true`. +/// When files differ, it samples the tail, midpoint, and quarter points to reject +/// non-identical files in O(1) time before committing to a full O(N) scan. +#[inline] +pub fn is_identical(expected: &[u8], actual: &[u8]) -> bool { + if expected.len() != actual.len() { + return false; + } + let len = expected.len(); + if len == 0 { + return true; + } + + if len >= 256 { + // Fast O(1) checks at tail and key sample points before full memcmp + if expected[len - 256..] != actual[len - 256..] { + return false; + } + let mid = len / 2; + if expected[mid - 128..mid + 128] != actual[mid - 128..mid + 128] { + return false; + } + let q1 = len / 4; + if expected[q1 - 128..q1 + 128] != actual[q1 - 128..q1 + 128] { + return false; + } + let q3 = 3 * len / 4; + if expected[q3 - 128..q3 + 128] != actual[q3 - 128..q3 + 128] { + return false; + } + } + + expected == actual +} + #[cfg(test)] pub mod testcmds { // Command construction wrapper that provides some validation and non-obscure, "fail fast" @@ -665,4 +702,53 @@ mod tests { assert!(m_time > current_time); } } + + mod is_identical { + use super::*; + + #[test] + fn test_empty() { + assert!(is_identical(b"", b"")); + assert!(!is_identical(b"", b"a")); + assert!(!is_identical(b"a", b"")); + } + + #[test] + fn test_small() { + assert!(is_identical(b"hello world", b"hello world")); + assert!(!is_identical(b"hello world", b"hello work!")); + assert!(!is_identical(b"hello", b"world")); + } + + #[test] + fn test_large_sample_rejections() { + let a = vec![b'a'; 1000]; + let mut b = vec![b'a'; 1000]; + assert!(is_identical(&a, &b)); + + // Differ at tail + b[999] = b'b'; + assert!(!is_identical(&a, &b)); + b[999] = b'a'; + + // Differ at midpoint + b[500] = b'b'; + assert!(!is_identical(&a, &b)); + b[500] = b'a'; + + // Differ at quarter 1 + b[250] = b'b'; + assert!(!is_identical(&a, &b)); + b[250] = b'a'; + + // Differ at quarter 3 + b[750] = b'b'; + assert!(!is_identical(&a, &b)); + b[750] = b'a'; + + // Differ at arbitrary position + b[10] = b'b'; + assert!(!is_identical(&a, &b)); + } + } } diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 6173c199..db0899de 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -1131,3 +1131,245 @@ fn label_errors(#[case] args: &[&str], #[case] error: &str) { .fails_with_code(2) .stderr_contains(error); } + +#[rstest] +// Symmetrical tie: repeated 'x' with shifting unique 'y' +#[case::abstract_symmetrical_tie("x\nx\ny\nx\nx\n", "x\ny\nx\nx\nx\n", "2d1\n< x\n3a3\n> x\n")] +// Asymmetrical tie 1: Delta = -1 (old has 4 lines, new has 5 lines) +#[case::asymmetric_tie_insert_bias( + "a\na\nb\na\n", + "a\nb\na\na\na\n", + "2d1\n< a\n3a3,4\n> a\n> a\n" +)] +// Asymmetrical tie 2: Delta = +1 (old has 5 lines, new has 4 lines) +#[case::asymmetric_tie_delete_bias( + "x\nx\nx\ny\nx\n", + "x\ny\nx\nx\n", + "2,3d1\n< x\n< x\n4a3\n> x\n" +)] +// Repeated brackets/braces near block end +#[case::braces_shift("}\n}\n}\nend\n", "}\n}\nend\n}\n", "3d2\n< }\n4a4\n> }\n")] +// Repeated code statements around unique variable assignment +#[case::code_statement_tie( + "fn test() {\n let a = 1;\n let a = 1;\n let a = 1;\n let b = 2;\n}\n", + "fn test() {\n let a = 1;\n let a = 1;\n let b = 2;\n let a = 1;\n}\n", + "4d3\n< let a = 1;\n5a5\n> let a = 1;\n" +)] +// Interleaved repeating pattern +#[case::interleaved_repeats( + "alpha\nbeta\nalpha\nbeta\nalpha\n", + "beta\nalpha\nbeta\nalpha\nbeta\n", + "1d0\n< alpha\n5a5\n> beta\n" +)] +// Repeated identical tokens at both start and end of hunk +#[case::repeated_anchors("A\nB\nA\nB\n", "B\nA\nB\nA\n", "1d0\n< A\n4a4\n> A\n")] +fn test_gnu_tie_breaking_edge_cases( + #[case] file1: &str, + #[case] file2: &str, + #[case] expected: &str, +) { + let (at, ts) = at_and_ts!(); + at.write("file1", file1); + at.write("file2", file2); + + ts.ucmd() + .args(&["file1", "file2"]) + .fails_with_code(1) + .stdout_is(expected); +} + +#[rstest] +// Simple 2-line adjacent swap +#[case::swap_adjacent_lines("alpha\nbeta\n", "beta\nalpha\n", "1d0\n< alpha\n2a2\n> alpha\n")] +// 3-line cyclic rotation (A B C -> B C A) +#[case::rotate_three_lines( + "first\nsecond\nthird\n", + "second\nthird\nfirst\n", + "1d0\n< first\n3a3\n> first\n" +)] +// 3-line full reversal (A B C -> C B A) +#[case::reverse_three_lines( + "one\ntwo\nthree\n", + "three\ntwo\none\n", + "1,2d0\n< one\n< two\n3a2,3\n> two\n> one\n" +)] +fn test_gnu_permutation_edge_cases( + #[case] file1: &str, + #[case] file2: &str, + #[case] expected: &str, +) { + let (at, ts) = at_and_ts!(); + at.write("file1", file1); + at.write("file2", file2); + + ts.ucmd() + .args(&["file1", "file2"]) + .fails_with_code(1) + .stdout_is(expected); +} + +#[rstest] +// Prepending lines at beginning of file +#[case::prepend_lines("two\nthree\n", "zero\none\ntwo\nthree\n", "0a1,2\n> zero\n> one\n")] +// Appending lines at end of file +#[case::append_lines("one\ntwo\n", "one\ntwo\nthree\nfour\n", "2a3,4\n> three\n> four\n")] +// Prepending AND appending in the same file +#[case::prepend_and_append("two\n", "one\ntwo\nthree\n", "0a1\n> one\n1a3\n> three\n")] +// Deleting all lines at the top of file +#[case::delete_head("one\ntwo\nthree\n", "three\n", "1,2d0\n< one\n< two\n")] +// Deleting all lines at the bottom of file +#[case::delete_tail("one\ntwo\nthree\n", "one\n", "2,3d1\n< two\n< three\n")] +// 100% disjoint files (every line replaced) +#[case::completely_different( + "foo\nbar\nbaz\n", + "one\ntwo\nthree\n", + "1,3c1,3\n< foo\n< bar\n< baz\n---\n> one\n> two\n> three\n" +)] +// Single character change +#[case::single_char_diff("a\n", "b\n", "1c1\n< a\n---\n> b\n")] +fn test_gnu_extremity_edge_cases(#[case] file1: &str, #[case] file2: &str, #[case] expected: &str) { + let (at, ts) = at_and_ts!(); + at.write("file1", file1); + at.write("file2", file2); + + ts.ucmd() + .args(&["file1", "file2"]) + .fails_with_code(1) + .stdout_is(expected); +} + +#[rstest] +// Many-to-one replacement +#[case::replace_many_to_one("a\nb\nc\n", "x\n", "1,3c1\n< a\n< b\n< c\n---\n> x\n")] +// One-to-many replacement +#[case::replace_one_to_many("x\n", "a\nb\nc\n", "1c1,3\n< x\n---\n> a\n> b\n> c\n")] +// Many-to-many replacement +#[case::replace_many_to_many( + "a\nb\nc\n", + "x\ny\nz\nw\n", + "1,3c1,4\n< a\n< b\n< c\n---\n> x\n> y\n> z\n> w\n" +)] +// Two distinct change hunks separated by common anchors +#[case::two_separated_hunks( + "hunk1_a\ncommon1\ncommon2\nhunk2_a\n", + "hunk1_b\ncommon1\ncommon2\nhunk2_b\n", + "1c1\n< hunk1_a\n---\n> hunk1_b\n4c4\n< hunk2_a\n---\n> hunk2_b\n" +)] +// Inserting unique lines into a block of repeated lines +#[case::insert_into_repeats( + "item\nitem\nitem\n", + "item\nitem\nnew_item\nitem\n", + "2a3\n> new_item\n" +)] +// Deleting unique line from a block of repeated lines +#[case::delete_from_repeats( + "item\nitem\nold_item\nitem\n", + "item\nitem\nitem\n", + "3d2\n< old_item\n" +)] +fn test_gnu_replacement_hunk_edge_cases( + #[case] file1: &str, + #[case] file2: &str, + #[case] expected: &str, +) { + let (at, ts) = at_and_ts!(); + at.write("file1", file1); + at.write("file2", file2); + + ts.ucmd() + .args(&["file1", "file2"]) + .fails_with_code(1) + .stdout_is(expected); +} + +#[rstest] +// Old file has no final newline, new file has newline +#[case::no_newline_old( + "hello", + "hello\n", + "1c1\n< hello\n\\ No newline at end of file\n---\n> hello\n" +)] +// Old file has newline, new file has no final newline +#[case::no_newline_new( + "hello\n", + "hello", + "1c1\n< hello\n---\n> hello\n\\ No newline at end of file\n" +)] +// Both files have no final newline and are different +#[case::both_no_newline( + "hello", + "world", + "1c1\n< hello\n\\ No newline at end of file\n---\n> world\n\\ No newline at end of file\n" +)] +// Multi-line file where replacement occurs on the line without newline +#[case::replace_on_unterminated_line( + "a\nb", + "a\nc", + "2c2\n< b\n\\ No newline at end of file\n---\n> c\n\\ No newline at end of file\n" +)] +fn test_gnu_missing_newline_edge_cases( + #[case] file1: &str, + #[case] file2: &str, + #[case] expected: &str, +) { + let (at, ts) = at_and_ts!(); + at.write("file1", file1); + at.write("file2", file2); + + ts.ucmd() + .args(&["file1", "file2"]) + .fails_with_code(1) + .stdout_is(expected); +} + +#[rstest] +#[case::unified_code_tie( + "fn test() {\n let a = 1;\n let a = 1;\n let a = 1;\n let b = 2;\n}\n", + "fn test() {\n let a = 1;\n let a = 1;\n let b = 2;\n let a = 1;\n}\n", + "@@ -1,6 +1,6 @@\n fn test() {\n let a = 1;\n let a = 1;\n- let a = 1;\n let b = 2;\n+ let a = 1;\n }\n" +)] +#[case::unified_swap_adjacent( + "apple\norange\nbanana\ngrape\n", + "apple\nbanana\norange\ngrape\n", + "@@ -1,4 +1,4 @@\n apple\n-orange\n banana\n+orange\n grape\n" +)] +#[case::unified_append( + "one\ntwo\n", + "one\ntwo\nthree\nfour\n", + "@@ -1,2 +1,4 @@\n one\n two\n+three\n+four\n" +)] +fn test_gnu_unified_diff_hunk_alignment( + #[case] file1: &str, + #[case] file2: &str, + #[case] expected_hunk: &str, +) { + let (at, ts) = at_and_ts!(); + at.write("file1", file1); + at.write("file2", file2); + + ts.ucmd() + .args(&["-u", "--label", "a", "--label", "b", "file1", "file2"]) + .fails_with_code(1) + .stdout_contains(expected_hunk); +} + +#[test] +fn test_large_input_diff() { + let (at, ts) = at_and_ts!(); + let mut file1 = String::new(); + let mut file2 = String::new(); + for i in 0..5000 { + file1.push_str(&format!("line {i}\n")); + if i == 2500 { + file2.push_str("modified line 2500\n"); + } else { + file2.push_str(&format!("line {i}\n")); + } + } + at.write("file1", &file1); + at.write("file2", &file2); + ts.ucmd() + .args(&["-u", "file1", "file2"]) + .fails_with_code(1) + .stdout_contains("@@ -2498,7 +2498,7 @@\n line 2497\n line 2498\n line 2499\n-line 2500\n+modified line 2500\n line 2501\n line 2502\n line 2503\n"); +}