diff --git a/Cargo.lock b/Cargo.lock index 79647b49..2e66e807 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -266,7 +266,6 @@ version = "0.6.0" dependencies = [ "codspeed-divan-compat", "ctor", - "diff", "itoa", "jiff 1.0.3", "pretty_assertions", diff --git a/Cargo.toml b/Cargo.toml index fe861335..c2c06eae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,6 @@ name = "diffutils" path = "src/main.rs" [dependencies] -diff = "0.1.13" itoa = "1.0.11" jiff = "1.0.2" regex = "1.10.4" diff --git a/src/context_diff.rs b/src/context_diff.rs index f02bcdd8..e0c226b1 100644 --- a/src/context_diff.rs +++ b/src/context_diff.rs @@ -7,6 +7,7 @@ use std::collections::VecDeque; use std::io::Write; use crate::params::Params; +use crate::ses; use crate::utils::{comparison_lines, do_write_line, line_prefix}; use crate::utils::{ get_modification_time, is_posix_locale, write_file_header, FunctionLineFinder, TimestampStyle, @@ -126,9 +127,10 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { 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( @@ -150,7 +152,7 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { 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( @@ -172,7 +174,7 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { 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/ed_diff.rs b/src/ed_diff.rs index 6cc8ae69..eb367e1a 100644 --- a/src/ed_diff.rs +++ b/src/ed_diff.rs @@ -6,6 +6,7 @@ use std::io::Write; use crate::params::Params; +use crate::ses; use crate::utils::{comparison_lines, do_write_line}; #[derive(Debug, PartialEq)] @@ -53,9 +54,10 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> 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) => { + ses::Change::Delete(str) => { if !mismatch.actual.is_empty() { results.push(mismatch); mismatch = Mismatch::new(line_number_expected, line_number_actual); @@ -63,11 +65,11 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { mismatch.expected.push(str.to_vec()); line_number_expected += 1; } - diff::Result::Right(str) => { + 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/lib.rs b/src/lib.rs index e1e43b6e..446a2943 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ pub mod ed_diff; pub mod macros; pub mod normal_diff; pub mod params; +pub mod ses; pub mod side_diff; pub mod unified_diff; pub mod utils; diff --git a/src/main.rs b/src/main.rs index 2be28099..6ddf1389 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,8 @@ use std::{ process::ExitCode, }; +use diffutilslib::ses; + mod bre; mod cmp; mod color; diff --git a/src/normal_diff.rs b/src/normal_diff.rs index c5ee5db2..ac8ba4ff 100644 --- a/src/normal_diff.rs +++ b/src/normal_diff.rs @@ -6,6 +6,7 @@ use std::io::Write; use crate::params::Params; +use crate::ses::{self, Change}; use crate::utils::{comparison_lines, do_write_line, line_prefix}; #[derive(Debug, PartialEq)] @@ -55,9 +56,10 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> 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); @@ -66,12 +68,12 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> 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, @@ -122,6 +124,7 @@ 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(); + let diff_results = make_diff(expected, actual, params); if params.brief && !diff_results.is_empty() { write!(&mut output, "\0").unwrap(); diff --git a/src/ses/algorithm/mod.rs b/src/ses/algorithm/mod.rs new file mode 100644 index 00000000..bcd18679 --- /dev/null +++ b/src/ses/algorithm/mod.rs @@ -0,0 +1,7 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +pub(crate) mod myers; +pub(crate) mod shift; diff --git a/src/ses/algorithm/myers.rs b/src/ses/algorithm/myers.rs new file mode 100644 index 00000000..b78f9df4 --- /dev/null +++ b/src/ses/algorithm/myers.rs @@ -0,0 +1,701 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use crate::ses::edit::{EditScript, Hunk}; +use std::ops::{Index, IndexMut, Range}; + +/// A storage buffer for diagonal endpoints, allowing natural mathematical +/// indexing with signed diagonal indices `k` in `[-max, max]`. +pub(crate) struct DiagonalBuffer { + offset: isize, + buffer: Vec, +} + +impl DiagonalBuffer { + /// Constructs a new `DiagonalBuffer` sized to store diagonals from `-max` to `+max` inclusive. + pub fn new(max: usize) -> Self { + Self { + offset: max as isize, + buffer: vec![0; 2 * max + 1], + } + } +} + +impl Index for DiagonalBuffer { + type Output = usize; + + #[inline] + fn index(&self, k: isize) -> &Self::Output { + &self.buffer[(k + self.offset) as usize] + } +} + +impl IndexMut for DiagonalBuffer { + #[inline] + fn index_mut(&mut self, k: isize) -> &mut Self::Output { + &mut self.buffer[(k + self.offset) as usize] + } +} + +/// Preallocated workspace holding forward (`vf`) and backward (`vb`) diagonal buffers, +/// allocated once at the start of the algorithm to avoid allocations in the diffing loop. +pub(crate) struct Workspace { + pub vf: DiagonalBuffer, + pub vb: DiagonalBuffer, +} + +impl Workspace { + /// Allocates forward and backward diagonal buffers for sequences of combined length `max`. + pub fn new(max: usize) -> Self { + Self { + vf: DiagonalBuffer::new(max), + vb: DiagonalBuffer::new(max), + } + } +} + +/// A maximal diagonal run of identical elements (`old[start_x..start_x + len] == new[start_y..start_y + len]`). +/// +/// In Myers' divide-and-conquer bisection, the middle snake connects +/// a forward furthest-reaching path with a backward furthest-reaching path. +/// Coordinates are expressed relative to the containing edit box. +/// +/// # Note on Myers' Paper Terminology +/// In Section 2 of Myers' 1986 paper (*"An O(ND) Difference Algorithm and Its Variations"*), +/// a "snake" is formally defined as an atomic search-frontier step: one edit move +/// (horizontal deletion or vertical insertion of cost 1) followed by zero or more diagonal edges +/// (matches of cost 0). +/// +/// In Section 4 (the linear-space divide-and-conquer refinement) and in this struct, +/// `Snake` represents strictly the maximal diagonal run of identical elements (`Δx == Δy == len`) +/// where the forward and backward search frontiers meet. The edit moves are not part of +/// the snake itself; they belong to the subproblems on either side of it. This ensures +/// `Δx == Δy == len` by construction and allows clean bisection of [`EditBox`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Snake { + pub start_x: usize, + pub start_y: usize, + pub len: usize, +} + +impl Snake { + /// Creates a new `Snake` starting at relative coordinates `(start_x, start_y)` of length `len`. + #[inline] + pub fn new(start_x: usize, start_y: usize, len: usize) -> Self { + Self { + start_x, + start_y, + len, + } + } + + /// End X-coordinate relative to the containing edit box (`start_x + len`). + #[inline] + pub fn end_x(&self) -> usize { + self.start_x + self.len + } + + /// End Y-coordinate relative to the containing edit box (`start_y + len`). + #[inline] + pub fn end_y(&self) -> usize { + self.start_y + self.len + } + + /// Returns `true` if this snake has zero length (a point match transition). + #[cfg(test)] + #[inline] + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +/// A 2D bounding box in the edit graph representing a diff subproblem. +/// +/// In Myers' 1986 paper (Section 4), sequence A runs along the horizontal X-axis +/// and sequence B runs along the vertical Y-axis. An `EditBox` bounds a 2D rectangle +/// `[old_range × new_range]` comparing `A[old_range]` against `B[new_range]`. +/// +/// It requires two independent ranges because insertions and deletions advance each +/// sequence at different rates, meaning each subproblem can have different start/end +/// offsets and lengths. +/// +/// Divide-and-conquer iteratively bisects this box around middle snakes into independent +/// left (top-left) and right (bottom-right) sub-boxes until reaching base cases (identical +/// matches or pure insertions/deletions) that emit as diff hunks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct EditBox { + /// Half-open range of indices in sequence A (horizontal X-axis). + pub old_range: Range, + /// Half-open range of indices in sequence B (vertical Y-axis). + pub new_range: Range, +} + +impl EditBox { + /// Constructs a new `EditBox` from old and new index ranges. + #[inline] + pub fn new(old_range: Range, new_range: Range) -> Self { + Self { + old_range, + new_range, + } + } + + /// Number of elements remaining in sequence A within this box. + #[inline] + pub fn old_len(&self) -> usize { + self.old_range.len() + } + + /// Number of elements remaining in sequence B within this box. + #[inline] + pub fn new_len(&self) -> usize { + self.new_range.len() + } + + /// Returns `true` if both old and new ranges are completely empty. + #[inline] + pub fn is_empty(&self) -> bool { + self.old_range.is_empty() && self.new_range.is_empty() + } + + /// Trims matching elements from the start of both ranges in-place, + /// advancing `old_range.start` and `new_range.start`. + pub fn trim_common_prefix(&mut self, mut equals: F) -> usize + where + F: FnMut(usize, usize) -> bool, + { + let mut count = 0; + while self.old_range.start < self.old_range.end + && self.new_range.start < self.new_range.end + && equals(self.old_range.start, self.new_range.start) + { + self.old_range.start += 1; + self.new_range.start += 1; + count += 1; + } + count + } + + /// Trims matching elements from the end of both ranges in-place, + /// decrementing `old_range.end` and `new_range.end`. + pub fn trim_common_suffix(&mut self, mut equals: F) -> usize + where + F: FnMut(usize, usize) -> bool, + { + let mut count = 0; + while self.old_range.start < self.old_range.end + && self.new_range.start < self.new_range.end + && equals(self.old_range.end - 1, self.new_range.end - 1) + { + self.old_range.end -= 1; + self.new_range.end -= 1; + count += 1; + } + count + } + + /// Bisects this edit box around a middle snake, producing independent `(left, right)` boxes. + /// + /// The snake itself represents identical tokens and is excluded from both boxes: + /// - `left` covers `(old_start..old_start + snake.start_x, new_start..new_start + snake.start_y)` + /// - `right` covers `(old_start + snake.end_x()..old_end, new_start + snake.end_y()..new_end)` + #[inline] + pub fn split_around(&self, snake: Snake) -> (EditBox, EditBox) { + let left = EditBox::new( + self.old_range.start..(self.old_range.start + snake.start_x), + self.new_range.start..(self.new_range.start + snake.start_y), + ); + let right = EditBox::new( + (self.old_range.start + snake.end_x())..self.old_range.end, + (self.new_range.start + snake.end_y())..self.new_range.end, + ); + (left, right) + } + + /// Converts an edit box where at least one side is empty into an edit `Hunk`. + #[inline] + pub fn into_hunk(self) -> Hunk { + Hunk::new(self.old_range, self.new_range) + } +} + +/// Greedily advances `(x, y)` along a forward diagonal while elements match. +#[inline] +pub(crate) fn extend_forward( + mut x: usize, + mut y: usize, + max_x: usize, + max_y: usize, + x_off: usize, + y_off: usize, + equals: &mut F, +) -> (usize, usize) +where + F: FnMut(usize, usize) -> bool, +{ + while x < max_x && y < max_y && equals(x_off + x, y_off + y) { + x += 1; + y += 1; + } + (x, y) +} + +/// Greedily retreats `(x, y)` along a backward diagonal while elements match. +#[inline] +pub(crate) fn extend_backward( + mut x: usize, + mut y: usize, + x_off: usize, + y_off: usize, + equals: &mut F, +) -> (usize, usize) +where + F: FnMut(usize, usize) -> bool, +{ + while x > 0 && y > 0 && equals(x_off + x - 1, y_off + y - 1) { + x -= 1; + y -= 1; + } + (x, y) +} + +/// Appends a `Hunk` to the list, coalescing it with the preceding hunk if they are adjacent or overlapping. +#[inline] +pub(crate) fn push_or_coalesce(hunks: &mut Vec, hunk: Hunk) { + if let Some(last) = hunks.last_mut() { + let last_old = last.old_range(); + let last_new = last.new_range(); + let hunk_old = hunk.old_range(); + let hunk_new = hunk.new_range(); + + if last_old.end >= hunk_old.start && last_new.end >= hunk_new.start { + *last = Hunk::new( + last_old.start..last_old.end.max(hunk_old.end), + last_new.start..last_new.end.max(hunk_new.end), + ); + return; + } + } + hunks.push(hunk); +} + +/// Computes the Shortest Edit Script (SES) in `O((N + M) * D)` time and `O(N + M)` space, +/// based on Eugene Myers' 1986 paper *"An O(ND) Difference Algorithm and Its Variations"*. +/// https://publications.mpi-cbg.de/Myers_1986_6330.pdf +/// +/// Myers models diffing as finding the shortest path across a 2D edit graph where deletions +/// and insertions cost 1, while identical diagonal matches cost 0. By exploring along +/// diagonals `k = x - y`, it greedily tracks the furthest-reaching paths for each edit step. +/// +/// This implementation maps Myers' linear-space refinement into an iterative architecture: +/// - `Workspace` hosts preallocated forward and backward diagonal buffers (`DiagonalBuffer` with `Index`), +/// - An explicit `EditBox` worklist replaces call-stack recursion to guarantee overflow safety, +/// - Bounding boxes bisect around bidirectional middle snakes until reaching base cases that coalesce into hunks. +/// +/// # Arguments +/// * `len_a` - Number of elements in sequence A. +/// * `len_b` - Number of elements in sequence B. +/// * `equals` - An index-based equality predicate `equals(i, j)` returning `true` if element `i` +/// in sequence A equals element `j` in sequence B. +pub(crate) fn myers(len_a: usize, len_b: usize, mut equals: F) -> EditScript +where + F: FnMut(usize, usize) -> bool, +{ + let mut ws = Workspace::new(len_a + len_b); + let mut hunks: Vec = Vec::new(); + + // Stack for iterative divide-and-conquer (avoids call stack overflow on large inputs) + let mut stack = Vec::with_capacity(32); + stack.push(EditBox::new(0..len_a, 0..len_b)); + + while let Some(mut edit_box) = stack.pop() { + // Fast-path: trim common prefixes and suffixes + edit_box.trim_common_prefix(&mut equals); + edit_box.trim_common_suffix(&mut equals); + + if edit_box.is_empty() { + continue; + } + + // Base cases: one or both sequences exhausted + if edit_box.old_len() == 0 || edit_box.new_len() == 0 { + push_or_coalesce(&mut hunks, edit_box.into_hunk()); + continue; + } + + // Bisect edit box around middle snake + if let Some(snake) = middle_snake(&edit_box, &mut equals, &mut ws) { + let (left, right) = edit_box.split_around(snake); + // Push right box first so that left box is popped first. + // This guarantees hunks are emitted in strictly ascending index order. + stack.push(right); + stack.push(left); + } else { + push_or_coalesce(&mut hunks, edit_box.into_hunk()); + } + } + + EditScript::new(hunks) +} + +/// Finds the middle snake in `O((N + M) * D)` time and `O(N + M)` space. +/// +/// Explores forward D-paths from `(0, 0)` (the start of `edit_box`) and backward +/// D-paths from `(N, M)` (the end of `edit_box`, where `N = edit_box.old_len()` +/// and `M = edit_box.new_len()`) until they overlap on the same diagonal `k`. +/// Reuses `ws` without dynamic allocations. +fn middle_snake(edit_box: &EditBox, equals: &mut F, ws: &mut Workspace) -> Option +where + F: FnMut(usize, usize) -> bool, +{ + let n = edit_box.old_len(); + let m = edit_box.new_len(); + let max = n + m; + let delta = n as isize - m as isize; + let odd = (delta & 1) != 0; + + let (vf, vb) = (&mut ws.vf, &mut ws.vb); + + // Initial endpoints: forward path at (0, 0) on diagonal k=0, + // backward path at (n, m) on diagonal k=delta + vf[0] = 0; + vb[delta] = n; + + let d_max = max.div_ceil(2); + let min_k = -(m as isize); + let max_k = n as isize; + + for d in 1..=d_max { + let d_isize = d as isize; + + // Forward search: explore D-paths from (0, 0) + // Descending order (.rev().step_by(2)) preserves GNU diff tie-breaking preference + for k in (-d_isize..=d_isize).rev().step_by(2) { + if k < min_k || k > max_k { + continue; + } + + let x_start = if k == -d_isize + || k == min_k + || (k != d_isize && k != max_k && vf[k - 1] < vf[k + 1]) + { + vf[k + 1] + } else { + vf[k - 1] + 1 + }; + + let y_start_isize = x_start as isize - k; + let (x0, y0) = (x_start, y_start_isize.max(0) as usize); + + let (x, _) = if y_start_isize >= 0 { + extend_forward( + x_start, + y_start_isize as usize, + n, + m, + edit_box.old_range.start, + edit_box.new_range.start, + equals, + ) + } else { + (x_start, 0) + }; + + vf[k] = x; // Record the furthest-reaching forward endpoint on diagonal k + + // If delta is odd, check if forward search overlaps backward search + if odd && k >= delta - (d_isize - 1) && k <= delta + (d_isize - 1) && vf[k] >= vb[k] { + let snake_len = x - x0; + return Some(Snake::new(x0, y0, snake_len)); + } + } + + // Backward search: explore D-paths backwards from (N, M) + for k in ((delta - d_isize)..=(delta + d_isize)).rev().step_by(2) { + if k < min_k || k > max_k { + continue; + } + + let u_start = if k == delta + d_isize || k == max_k { + vb[k - 1] + } else if k == delta - d_isize || k == min_k { + vb[k + 1].saturating_sub(1) + } else if vb[k - 1] < vb[k + 1].saturating_sub(1) { + vb[k - 1] + } else { + vb[k + 1].saturating_sub(1) + }; + + let v_start_isize = u_start as isize - k; + let u0 = u_start; + + let (u, v) = if v_start_isize >= 0 { + extend_backward( + u_start, + v_start_isize as usize, + edit_box.old_range.start, + edit_box.new_range.start, + equals, + ) + } else { + (u_start, 0) + }; + vb[k] = u; + + // If delta is even, check if backward search overlaps forward search + if !odd && k >= -d_isize && k <= d_isize && vf[k] >= vb[k] { + let snake_len = u0 - u; + return Some(Snake::new(u, v, snake_len)); + } + } + } + + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_myers_identical() { + let a = ["a", "b", "c"]; + let b = ["a", "b", "c"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert!(script.hunks().is_empty()); + } + + #[test] + fn test_myers_delete_middle() { + let a = ["a", "b", "c"]; + let b = ["a", "c"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert_eq!(script.hunks().len(), 1); + assert_eq!(script.hunks()[0].old_range(), 1..2); + assert_eq!(script.hunks()[0].new_range(), 1..1); + } + + #[test] + fn test_myers_insert_middle() { + let a = ["a", "c"]; + let b = ["a", "b", "c"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert_eq!(script.hunks().len(), 1); + assert_eq!(script.hunks()[0].old_range(), 1..1); + assert_eq!(script.hunks()[0].new_range(), 1..2); + } + + #[test] + fn test_myers_complex() { + // Myers 1986 paper example: A = "ABCABBA", B = "CBABAC" + // Optimal D = 5: LCS is ["C", "B", "B", "A"] (length 4) + let a = ["A", "B", "C", "A", "B", "B", "A"]; + let b = ["C", "B", "A", "B", "A", "C"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + + assert_eq!(script.hunks().len(), 4); + assert_eq!(script.hunks()[0].old_range(), 0..2); // Delete "A", "B" + assert_eq!(script.hunks()[0].new_range(), 0..0); + assert_eq!(script.hunks()[1].old_range(), 3..4); // Delete "A" + assert_eq!(script.hunks()[1].new_range(), 1..1); + assert_eq!(script.hunks()[2].old_range(), 5..5); // Insert "A" + assert_eq!(script.hunks()[2].new_range(), 2..3); + assert_eq!(script.hunks()[3].old_range(), 7..7); // Insert "C" + assert_eq!(script.hunks()[3].new_range(), 5..6); + } + + #[test] + fn test_myers_both_empty() { + let a: [&str; 0] = []; + let b: [&str; 0] = []; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert!(script.hunks().is_empty()); + } + + #[test] + fn test_myers_empty_to_nonempty() { + let a: [&str; 0] = []; + let b = ["x", "y"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert_eq!(script.hunks().len(), 1); + assert_eq!(script.hunks()[0].old_range(), 0..0); + assert_eq!(script.hunks()[0].new_range(), 0..2); + } + + #[test] + fn test_myers_nonempty_to_empty() { + let a = ["x", "y"]; + let b: [&str; 0] = []; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert_eq!(script.hunks().len(), 1); + assert_eq!(script.hunks()[0].old_range(), 0..2); + assert_eq!(script.hunks()[0].new_range(), 0..0); + } + + #[test] + fn test_myers_completely_disjoint() { + let a = ["1", "2", "3"]; + let b = ["4", "5", "6"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert_eq!(script.hunks().len(), 1); + assert_eq!(script.hunks()[0].old_range(), 0..3); + assert_eq!(script.hunks()[0].new_range(), 0..3); + } + + #[test] + fn test_myers_repeated_elements() { + let a = ["a", "a", "a"]; + let b = ["a", "a"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + assert_eq!(script.hunks().len(), 1); + assert_eq!(script.hunks()[0].old_range().len(), 1); + assert_eq!(script.hunks()[0].new_range().len(), 0); + } + + #[test] + fn test_push_or_coalesce() { + let mut hunks = Vec::new(); + // Adjacent deletion and insertion at the same position should merge into a replacement + push_or_coalesce(&mut hunks, Hunk::new(1..2, 1..1)); // Delete index 1 + push_or_coalesce(&mut hunks, Hunk::new(2..2, 1..2)); // Insert at index 1 + push_or_coalesce(&mut hunks, Hunk::new(5..7, 4..4)); // Separate disjoint deletion + + assert_eq!(hunks.len(), 2); + assert_eq!(hunks[0].old_range(), 1..2); + assert_eq!(hunks[0].new_range(), 1..2); + assert_eq!(hunks[1].old_range(), 5..7); + assert_eq!(hunks[1].new_range(), 4..4); + } + + #[test] + fn test_myers_paper_1986() { + // The example in Eugene W Myers paper + let a = ["C", "B", "A", "B", "A", "C"]; + let b = ["A", "B", "C", "A", "B", "B", "A"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + // Optimal D = 5: matches B, A, B, A (length 4) + assert_eq!(script.hunks().len(), 4); + assert_eq!(script.hunks()[0].old_range(), 0..1); // Delete C + assert_eq!(script.hunks()[0].new_range(), 0..1); // Replace with A + assert_eq!(script.hunks()[1].old_range(), 2..2); // Insert C + assert_eq!(script.hunks()[1].new_range(), 2..3); + assert_eq!(script.hunks()[2].old_range(), 4..4); // Insert B + assert_eq!(script.hunks()[2].new_range(), 5..6); + assert_eq!(script.hunks()[3].old_range(), 5..6); // Delete C + assert_eq!(script.hunks()[3].new_range(), 7..7); + } + + #[test] + fn test_myers_gnu_diff_alignment_fruits() { + let a = ["banana", "mango", "carrot", "grapes", "apple"]; + let b = ["apple", "banana", "mango", "grapes", "carrot"]; + let script = myers(a.len(), b.len(), |i, j| a[i] == b[j]); + // Matches banana, mango, grapes (LCS length 3, D = 4) + assert_eq!(script.hunks().len(), 3); + assert_eq!(script.hunks()[0].old_range(), 0..0); // Insert apple + assert_eq!(script.hunks()[0].new_range(), 0..1); + assert_eq!(script.hunks()[1].old_range(), 2..3); // Delete carrot + assert_eq!(script.hunks()[1].new_range(), 3..3); + assert_eq!(script.hunks()[2].old_range(), 4..5); // Replace apple with carrot + assert_eq!(script.hunks()[2].new_range(), 4..5); + } + + #[test] + fn test_diagonal_buffer_indexing_and_mutation() { + let mut buf = DiagonalBuffer::new(4); + + buf[-4] = 42; + buf[0] = 100; + buf[4] = 999; + buf[-1] = buf[0] + 5; + + assert_eq!(buf[-4], 42); + assert_eq!(buf[0], 100); + assert_eq!(buf[4], 999); + assert_eq!(buf[-1], 105); + } + + #[test] + fn test_workspace_buffers() { + let mut ws = Workspace::new(5); + ws.vf[0] = 10; + ws.vf[-5] = 20; + ws.vf[5] = 30; + + ws.vb[0] = 50; + ws.vb[-5] = 60; + ws.vb[5] = 70; + + assert_eq!(ws.vf[0], 10); + assert_eq!(ws.vf[-5], 20); + assert_eq!(ws.vf[5], 30); + assert_eq!(ws.vb[0], 50); + assert_eq!(ws.vb[-5], 60); + assert_eq!(ws.vb[5], 70); + } + + #[test] + fn test_snake_properties() { + let empty_snake = Snake::new(2, 3, 0); + assert!(empty_snake.is_empty()); + assert_eq!(empty_snake.len, 0); + assert_eq!(empty_snake.end_x(), 2); + assert_eq!(empty_snake.end_y(), 3); + + let active_snake = Snake::new(1, 2, 3); + assert!(!active_snake.is_empty()); + assert_eq!(active_snake.len, 3); + assert_eq!(active_snake.end_x(), 4); + assert_eq!(active_snake.end_y(), 5); + } + + #[test] + fn test_extend_forward_and_backward() { + let a = ["a", "b", "c", "d"]; + let b = ["x", "b", "c", "y"]; + let mut equals = |i, j| a[i] == b[j]; + + // Forward extension: starting at (1, 1), offset (0, 0) + let (x, y) = extend_forward(1, 1, 4, 4, 0, 0, &mut equals); + assert_eq!((x, y), (3, 3)); + + // Backward extension: starting backwards from (3, 3), offset (0, 0) + let (x, y) = extend_backward(3, 3, 0, 0, &mut equals); + assert_eq!((x, y), (1, 1)); + } + + #[test] + fn test_edit_box_trimming_and_splitting() { + let a = ["header", "a", "b", "footer"]; + let b = ["header", "x", "footer"]; + let mut equals = |i, j| a[i] == b[j]; + + let mut box_ = EditBox::new(0..a.len(), 0..b.len()); + assert_eq!(box_.trim_common_prefix(&mut equals), 1); + assert_eq!(box_.old_range, 1..4); + assert_eq!(box_.new_range, 1..3); + + assert_eq!(box_.trim_common_suffix(&mut equals), 1); + assert_eq!(box_.old_range, 1..3); // "a", "b" + assert_eq!(box_.new_range, 1..2); // "x" + + // Split around a snake at relative (1, 0) of len 0 + let snake = Snake::new(1, 0, 0); + let (left, right) = box_.split_around(snake); + assert_eq!(left.old_range, 1..2); + assert_eq!(left.new_range, 1..1); + assert_eq!(right.old_range, 2..3); + assert_eq!(right.new_range, 1..2); + } + + #[test] + fn test_edit_box_into_hunk() { + let box_ = EditBox::new(2..5, 3..3); + let hunk = box_.into_hunk(); + assert_eq!(hunk.old_range(), 2..5); + assert_eq!(hunk.new_range(), 3..3); + assert!(hunk.new_range().is_empty()); + } +} diff --git a/src/ses/algorithm/shift.rs b/src/ses/algorithm/shift.rs new file mode 100644 index 00000000..a4ddee09 --- /dev/null +++ b/src/ses/algorithm/shift.rs @@ -0,0 +1,235 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use crate::ses::{ + edit::{EditScript, Hunk}, + optimize::bitset::Bitset, +}; + +/// Adjusts insertion and deletion boundaries across identical elements +/// to merge adjacent changes and prefer cleaner, intuitive diff boundaries. +/// +/// When identical elements appear at the edges of an edit (such as repeated +/// lines, blank lines, or closing delimiters), an edit can mathematically be +/// placed at multiple valid positions with identical minimal edit distance. +/// Boundary shifting slides the changes to join separate hunks whenever +/// possible, favoring shifts toward earlier matching positions to coalesce +/// changes, and moving forward to place changes at natural boundaries. +pub(crate) fn shift_boundaries(a: &[T], b: &[T], hunks: &[Hunk], mut equals: F) -> EditScript +where + F: FnMut(&T, &T) -> bool, +{ + let n = a.len(); + let m = b.len(); + + // If there are no hunks or either sequence is empty, no shifts can occur. + if hunks.is_empty() { + return EditScript::default(); + } + + if n == 0 || m == 0 { + return EditScript::new(hunks.to_vec()); + } + + // Boolean masks tracking modified elements in each sequence. + let mut changed_a = Bitset::new(n); + let mut changed_b = Bitset::new(m); + + // Mark all changed ranges directly using slice operations. + for hunk in hunks { + changed_a.set_range(hunk.old_range()); + changed_b.set_range(hunk.new_range()); + } + + // Shift deletions (sequence A) against insertions (sequence B), + // then shift insertions (sequence B) against deletions (sequence A). + shift_sequence(a, &mut changed_a, &changed_b, &mut equals); + shift_sequence(b, &mut changed_b, &changed_a, &mut equals); + + // Reconstruct coalesced hunks from the adjusted masks. + reconstruct_hunks(&changed_a, &changed_b, hunks.len()) +} + +/// Shifts change boundaries for a single sequence against the other sequence's changes. +fn shift_sequence(elements: &[T], changed: &mut Bitset, other_changed: &Bitset, mut equals: F) +where + F: FnMut(&T, &T) -> bool, +{ + let len = elements.len(); + let other_len = other_changed.len(); + let mut i = 0; + let mut j = 0; + + while i < len { + // Advance i and j together through unchanged elements. + while i < len && !changed.get(i) { + advance_other_unchanged(other_changed, &mut j); + i += 1; + } + + if i >= len { + break; + } + + let mut start = i; + + // Find the end of this run of changes. + i += 1; + while i < len && changed.get(i) { + i += 1; + } + while j < other_len && other_changed.get(j) { + j += 1; + } + + let mut corresponding; + + loop { + let runlength = i - start; + + // Backward shift: while previous unchanged element matches the last changed element. + // This merges with preceding changed regions whenever possible. + while start > 0 && equals(&elements[start - 1], &elements[i - 1]) { + start -= 1; + i -= 1; + changed.set(start); + changed.clear(i); + + while start > 0 && changed.get(start - 1) { + start -= 1; + } + step_back_other_unchanged(other_changed, &mut j); + } + + // Record whether this changed run corresponds to a change in the other sequence. + corresponding = if is_corresponding(other_changed, j) { + i + } else { + len + }; + + // Forward shift: while first changed element matches following unchanged element. + // This merges with subsequent changed regions. + while i < len && equals(&elements[start], &elements[i]) { + changed.clear(start); + changed.set(i); + start += 1; + i += 1; + + while i < len && changed.get(i) { + i += 1; + } + + step_forward_other_unchanged(other_changed, &mut j, i, &mut corresponding); + } + + // Stop when shifting ceases to change the run length (no new merges). + if runlength == i - start { + break; + } + } + + // Move back to the corresponding run in the other sequence if shifted too far. + while corresponding < i { + start -= 1; + i -= 1; + changed.set(start); + changed.clear(i); + + step_back_other_unchanged(other_changed, &mut j); + } + } +} + +/// Advances `j` in the other sequence past any changes and one matching unchanged element. +#[inline] +fn advance_other_unchanged(other: &Bitset, j: &mut usize) { + while *j < other.len() && other.get(*j) { + *j += 1; + } + if *j < other.len() { + *j += 1; + } +} + +/// Steps `j` backward in the other sequence past one matching unchanged element +/// and any preceding changes. +#[inline] +fn step_back_other_unchanged(other: &Bitset, j: &mut usize) { + if *j > 0 { + *j -= 1; + while *j > 0 && other.get(*j) { + *j -= 1; + } + } +} + +/// Steps `j` forward in the other sequence past one matching unchanged element +/// and following changes, updating the correspondence index. +#[inline] +fn step_forward_other_unchanged( + other: &Bitset, + j: &mut usize, + i: usize, + corresponding: &mut usize, +) { + *j += 1; + while *j < other.len() && other.get(*j) { + *corresponding = i; + *j += 1; + } +} + +/// Returns true if the element immediately preceding `j` in the other sequence is changed. +#[inline] +fn is_corresponding(other: &Bitset, j: usize) -> bool { + j > 0 && j - 1 < other.len() && other.get(j - 1) +} + +/// Reconstructs coalesced hunks by scanning backward from the ends of both sequences. +fn reconstruct_hunks(changed_a: &Bitset, changed_b: &Bitset, capacity_hint: usize) -> EditScript { + let mut hunks = Vec::with_capacity(capacity_hint); + let mut i = changed_a.len(); + let mut j = changed_b.len(); + + while i > 0 || j > 0 { + if (i > 0 && changed_a.get(i - 1)) || (j > 0 && changed_b.get(j - 1)) { + let old_end = i; + while i > 0 && changed_a.get(i - 1) { + i -= 1; + } + let old_start = i; + + let new_end = j; + while j > 0 && changed_b.get(j - 1) { + j -= 1; + } + let new_start = j; + + hunks.push(Hunk::new(old_start..old_end, new_start..new_end)); + } else { + i = i.saturating_sub(1); + j = j.saturating_sub(1); + } + } + + hunks.reverse(); + EditScript::new(hunks) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_shift_identical_repeat() { + let a = ["x", "a", "a", "a", "y"]; + let b = ["x", "a", "a", "y"]; + let initial_hunks = vec![Hunk::new(1..2, 1..1)]; + let shifted = shift_boundaries(&a, &b, &initial_hunks, |x, y| x == y); + assert_eq!(shifted.hunks().len(), 1); + assert_eq!(shifted.hunks()[0].old_range(), 3..4); + } +} diff --git a/src/ses/change.rs b/src/ses/change.rs new file mode 100644 index 00000000..18701596 --- /dev/null +++ b/src/ses/change.rs @@ -0,0 +1,176 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use crate::ses::edit::EditScript; + +/// Edit operation on an individual element between two sequences. +#[derive(Debug, PartialEq, Eq)] +pub enum Change<'a, T> { + /// Element present and equal in both sequences. + Equal(&'a T, &'a T), + /// Element removed from the original sequence. + Delete(&'a T), + /// Element added to the modified sequence. + Insert(&'a T), +} + +impl<'a, T> Clone for Change<'a, T> { + fn clone(&self) -> Self { + *self + } +} + +impl<'a, T> Copy for Change<'a, T> {} + +/// Zero-copy lazy iterator yielding [`Change`] items without recursion. +pub struct ChangesIter<'s, 'a, T> { + old: &'a [T], + new: &'a [T], + script: &'s EditScript, + hunk_idx: usize, + old_idx: usize, + new_idx: usize, + insert_idx: usize, +} + +impl<'s, 'a, T> ChangesIter<'s, 'a, T> { + pub(crate) fn new(script: &'s EditScript, old: &'a [T], new: &'a [T]) -> Self { + Self { + old, + new, + script, + hunk_idx: 0, + old_idx: 0, + new_idx: 0, + insert_idx: 0, + } + } +} + +impl<'s, 'a, T> Iterator for ChangesIter<'s, 'a, T> { + type Item = Change<'a, T>; + + fn next(&mut self) -> Option { + let hunks = self.script.hunks(); + + loop { + if self.hunk_idx < hunks.len() { + let hunk = &hunks[self.hunk_idx]; + let old_r = hunk.old_range(); + let new_r = hunk.new_range(); + + if self.old_idx < old_r.start { + let old_item = &self.old[self.old_idx]; + let new_item = &self.new[self.new_idx]; + self.old_idx += 1; + self.new_idx += 1; + return Some(Change::Equal(old_item, new_item)); + } + + if self.old_idx < old_r.end { + let item = &self.old[self.old_idx]; + self.old_idx += 1; + return Some(Change::Delete(item)); + } + + let ins_pos = new_r.start + self.insert_idx; + if ins_pos < new_r.end { + let item = &self.new[ins_pos]; + self.insert_idx += 1; + self.new_idx += 1; + return Some(Change::Insert(item)); + } + + self.hunk_idx += 1; + self.insert_idx = 0; + continue; + } + + if self.old_idx < self.old.len() { + let old_item = &self.old[self.old_idx]; + let new_item = &self.new[self.new_idx]; + self.old_idx += 1; + self.new_idx += 1; + return Some(Change::Equal(old_item, new_item)); + } + + return None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ses::diff_lines; + + #[test] + fn test_iter_changes() { + let a = ["a", "b"]; + let b = ["a", "c"]; + let diff = diff_lines(&a, &b); + + let changes: Vec<_> = diff.iter_changes().collect(); + assert_eq!( + changes, + vec![ + Change::Equal(&"a", &"a"), + Change::Delete(&"b"), + Change::Insert(&"c"), + ] + ); + } + + #[test] + fn test_iter_changes_preserves_both_equal_items() { + #[derive(Debug)] + struct Normalized<'a> { + raw: &'a [u8], + key: &'a [u8], + } + impl PartialEq for Normalized<'_> { + fn eq(&self, other: &Self) -> bool { + self.key == other.key + } + } + impl AsRef<[u8]> for Normalized<'_> { + fn as_ref(&self) -> &[u8] { + self.key + } + } + + let a = [ + Normalized { + raw: b"\ta", + key: b" a", + }, + Normalized { + raw: b"b", + key: b"b", + }, + ]; + let b = [ + Normalized { + raw: b" a", + key: b" a", + }, + Normalized { + raw: b"b", + key: b"b", + }, + ]; + + let diff = diff_lines(&a, &b); + let changes: Vec<_> = diff.iter_changes().collect(); + assert_eq!(changes.len(), 2); + match changes[0] { + Change::Equal(left, right) => { + assert_eq!(left.raw, b"\ta"); + assert_eq!(right.raw, b" a"); + } + other => panic!("expected Equal, got {other:?}"), + } + } +} diff --git a/src/ses/diff.rs b/src/ses/diff.rs new file mode 100644 index 00000000..2f0844bd --- /dev/null +++ b/src/ses/diff.rs @@ -0,0 +1,127 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use crate::ses::edit::EditScript; +#[cfg(test)] +use crate::ses::edit::Hunk; + +/// Computed shortest edit script paired with borrowed input sequences. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Diff<'a, T> { + pub(crate) script: EditScript, + pub(crate) old: &'a [T], + pub(crate) new: &'a [T], +} + +impl<'a, T> Diff<'a, T> { + #[inline] + pub(crate) fn from_parts(script: EditScript, old: &'a [T], new: &'a [T]) -> Self { + debug_assert!( + Self::is_valid(&script, old.len(), new.len()), + "invalid edit script: hunks do not match slice dimensions or are non-monotonic" + ); + Self { script, old, new } + } + + pub(crate) fn is_valid(script: &EditScript, old_len: usize, new_len: usize) -> bool { + let hunks = script.hunks(); + + if hunks.is_empty() { + return old_len == new_len; + } + + let mut prev_old_end = 0; + let mut prev_new_end = 0; + + for hunk in hunks { + let old_r = hunk.old_range(); + let new_r = hunk.new_range(); + + if old_r.start > old_r.end || old_r.end > old_len { + return false; + } + if new_r.start > new_r.end || new_r.end > new_len { + return false; + } + if old_r.is_empty() && new_r.is_empty() { + return false; + } + if old_r.start < prev_old_end || new_r.start < prev_new_end { + return false; + } + if (old_r.start - prev_old_end) != (new_r.start - prev_new_end) { + return false; + } + + prev_old_end = old_r.end; + prev_new_end = new_r.end; + } + + (old_len - prev_old_end) == (new_len - prev_new_end) + } + + #[cfg(test)] + pub(crate) fn hunks(&self) -> &[Hunk] { + self.script.hunks() + } + + /// Lazily iterates over individual item changes (`Equal`, `Delete`, `Insert`). + pub fn iter_changes(&self) -> crate::ses::ChangesIter<'_, 'a, T> { + crate::ses::ChangesIter::new(&self.script, self.old, self.new) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_diff_validation_valid_cases() { + assert!(Diff::::is_valid(&EditScript::default(), 0, 0)); + assert!(Diff::::is_valid(&EditScript::default(), 5, 5)); + + let ins = Hunk::new(1..1, 1..2); + assert!(Diff::::is_valid(&EditScript::new(vec![ins]), 2, 3)); + + let del = Hunk::new(0..1, 0..0); + assert!(Diff::::is_valid(&EditScript::new(vec![del]), 2, 1)); + + let h1 = Hunk::new(1..2, 1..1); + let h2 = Hunk::new(3..3, 2..3); + assert!(Diff::::is_valid(&EditScript::new(vec![h1, h2]), 4, 4)); + } + + #[test] + fn test_diff_validation_invalid_cases() { + assert!(!Diff::::is_valid(&EditScript::default(), 5, 2)); + + let out_of_bounds = Hunk::new(0..5, 0..1); + assert!(!Diff::::is_valid( + &EditScript::new(vec![out_of_bounds]), + 3, + 3 + )); + + let h1 = Hunk::new(0..2, 0..1); + let h2 = Hunk::new(1..3, 1..2); + assert!(!Diff::::is_valid(&EditScript::new(vec![h1, h2]), 4, 4)); + + let h1 = Hunk::new(0..1, 0..1); + let h2 = Hunk::new(3..4, 2..3); + assert!(!Diff::::is_valid(&EditScript::new(vec![h1, h2]), 4, 4)); + + let h = Hunk::new(0..1, 0..1); + assert!(!Diff::::is_valid(&EditScript::new(vec![h]), 3, 2)); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "invalid edit script")] + fn test_diff_from_parts_panics_on_mismatched_empty_script() { + let old = [1, 2, 3]; + let new = [1]; + let _ = Diff::from_parts(EditScript::default(), &old, &new); + } +} diff --git a/src/ses/edit.rs b/src/ses/edit.rs new file mode 100644 index 00000000..6bdc63d3 --- /dev/null +++ b/src/ses/edit.rs @@ -0,0 +1,74 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use std::ops::Range; + +/// A single edit hunk (`old_range` removed from A, `new_range` inserted from B). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Hunk { + old_range: Range, + new_range: Range, +} + +impl Hunk { + pub(crate) fn new(old_range: Range, new_range: Range) -> Self { + Self { + old_range, + new_range, + } + } + + #[inline] + pub(crate) fn old_range(&self) -> Range { + self.old_range.clone() + } + + #[inline] + pub(crate) fn new_range(&self) -> Range { + self.new_range.clone() + } +} + +/// Non-overlapping, monotonic sequence of edit [`Hunk`]s. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct EditScript { + hunks: Vec, +} + +impl EditScript { + pub(crate) fn new(hunks: Vec) -> Self { + Self { hunks } + } + + pub(crate) fn hunks(&self) -> &[Hunk] { + &self.hunks + } + + pub(crate) fn into_hunks(self) -> Vec { + self.hunks + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_empty_edit_script() { + let script = EditScript::default(); + assert!(script.hunks().is_empty()); + } + + #[test] + fn test_hunk_ranges() { + let hunk = Hunk::new(0..2, 0..1); + assert_eq!(hunk.old_range(), 0..2); + assert_eq!(hunk.new_range(), 0..1); + + let script = EditScript::new(vec![hunk.clone()]); + assert_eq!(script.hunks(), &[hunk.clone()]); + assert_eq!(script.into_hunks(), vec![hunk]); + } +} diff --git a/src/ses/mod.rs b/src/ses/mod.rs new file mode 100644 index 00000000..ed0da865 --- /dev/null +++ b/src/ses/mod.rs @@ -0,0 +1,174 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +//! Zero-dependency, linear-space Myers diff engine (`O((N + M) D)` time, `O(N + M)` space). +//! +//! Computes the Shortest Edit Script between two sequences using: +//! - Common prefix/suffix pruning (`O(N)` fast-path) +//! - Token interning into `u32` IDs via an internal `FxHashMap` +//! - Bidirectional middle-snake divide-and-conquer with a single reusable diagonal `Workspace` +//! - Semantic boundary shifting matching GNU `diff` hunk alignment + +pub(crate) mod algorithm; +mod change; +mod diff; +mod edit; +pub(crate) mod optimize; + +pub use change::{Change, ChangesIter}; +pub use diff::Diff; + +use edit::{EditScript, Hunk}; + +/// Computes a line-by-line diff across pre-split slices using collision-free token interning. +/// +/// # Examples +/// +/// ```rust +/// use diffutilslib::ses::{diff_lines, Change}; +/// +/// let old = ["line 1", "line 2", "line 3"]; +/// let new = ["line 1", "line 2 modified", "line 3"]; +/// let diff = diff_lines(&old, &new); +/// +/// let changes: Vec<_> = diff.iter_changes().collect(); +/// assert_eq!(changes[1], Change::Delete(&"line 2")); +/// assert_eq!(changes[2], Change::Insert(&"line 2 modified")); +/// ``` +pub fn diff_lines<'a, T>(old: &'a [T], new: &'a [T]) -> Diff<'a, T> +where + T: AsRef<[u8]> + PartialEq, +{ + let trimmed = optimize::trim::trim_slices(old, new, |x, y| x == y); + + if trimmed.slice_a.is_empty() && trimmed.slice_b.is_empty() { + return Diff::from_parts(EditScript::default(), old, new); + } + + let mut interner = optimize::intern::TokenInterner::with_capacity( + trimmed.slice_a.len() + trimmed.slice_b.len(), + ); + let old_tokens = interner.intern(trimmed.slice_a); + let new_tokens = interner.intern(trimmed.slice_b); + + let script = algorithm::myers::myers(old_tokens.len(), new_tokens.len(), |i, j| { + old_tokens[i] == new_tokens[j] + }); + + let shifted = + algorithm::shift::shift_boundaries(&old_tokens, &new_tokens, script.hunks(), |x, y| x == y); + + let mut final_hunks = Vec::with_capacity(shifted.hunks().len()); + for hunk in shifted.into_hunks() { + let old_r = hunk.old_range(); + let new_r = hunk.new_range(); + final_hunks.push(Hunk::new( + old_r.start + trimmed.prefix_len..old_r.end + trimmed.prefix_len, + new_r.start + trimmed.prefix_len..new_r.end + trimmed.prefix_len, + )); + } + + Diff::from_parts(EditScript::new(final_hunks), old, new) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_diff_lines() { + let old = ["line 1", "line 2", "line 3"]; + let new = ["line 1", "line 2 modified", "line 3"]; + let diff = diff_lines(&old, &new); + + assert_eq!(diff.hunks().len(), 1); + assert_eq!(diff.hunks()[0].old_range(), 1..2); + assert_eq!(diff.hunks()[0].new_range(), 1..2); + } + + #[test] + fn test_diff_byte_lines() { + let old: [&[u8]; 3] = [b"line 1\n", b"line 2\n", b"line 3\n"]; + let new: [&[u8]; 3] = [b"line 1\n", b"line 2 modified\n", b"line 3\n"]; + let diff = diff_lines(&old, &new); + + assert_eq!(diff.hunks().len(), 1); + assert_eq!(diff.hunks()[0].old_range(), 1..2); + assert_eq!(diff.hunks()[0].new_range(), 1..2); + } + + #[test] + fn test_diff_lines_boundary_shifting() { + let old = ["x", "a", "a", "a", "y"]; + let new = ["x", "a", "a", "y"]; + let diff = diff_lines(&old, &new); + + assert_eq!(diff.hunks().len(), 1); + assert_eq!(diff.hunks()[0].old_range(), 3..4); + } + + #[test] + fn test_gnu_compat_edge_cases() { + type ExpectedHunk = (std::ops::Range, std::ops::Range); + type EdgeCase<'a> = (&'a [&'a str], &'a [&'a str], &'a [ExpectedHunk]); + + let cases: &[EdgeCase<'_>] = &[ + ( + &["fn foo() {", " body();", "}", ""], + &[ + "fn foo() {", + " body();", + "}", + "", + "fn bar() {", + " body();", + "}", + "", + ], + &[(4..4, 4..8)], + ), + ( + &["header", "item", "item", "footer"], + &["header", "item", "footer"], + &[(2..3, 2..2)], + ), + ( + &["if cond {", " a();", "}", "else {", " b();", "}"], + &["if cond {", " a();", "}"], + &[(3..6, 3..3)], + ), + ( + &["x", "a", "c", "d", "d", "a", "d", "c", "d", "c", "y"], + &["x", "b", "b", "b", "a", "a", "d", "a", "y"], + &[(1..1, 1..4), (2..5, 5..5), (7..10, 7..8)], + ), + ( + &["a", "b", "a", "b", "a", "b"], + &["b", "a", "b", "a"], + &[(0..1, 0..0), (5..6, 4..4)], + ), + ( + &["a", "b", "c", "d", "e"], + &["e", "d", "c", "b", "a"], + &[(0..4, 0..0), (5..5, 1..5)], + ), + ( + &["d", "c", "d"], + &["c", "d", "b", "a", "e", "d"], + &[(0..1, 0..0), (2..2, 1..5)], + ), + ]; + + for &(a, b, expected) in cases { + let diff = diff_lines(a, b); + let actual: Vec<_> = diff + .hunks() + .iter() + .map(|h| (h.old_range(), h.new_range())) + .collect(); + assert_eq!(actual, expected, "mismatch for a={a:?}, b={b:?}"); + } + } +} diff --git a/src/ses/optimize/bitset.rs b/src/ses/optimize/bitset.rs new file mode 100644 index 00000000..502f6a8f --- /dev/null +++ b/src/ses/optimize/bitset.rs @@ -0,0 +1,213 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +const BITS_PER_WORD: usize = 64; + +/// A compact fixed-capacity bitset backed by packed `u64` words. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Bitset { + words: Vec, + len: usize, +} + +impl Bitset { + /// Creates a new `Bitset` of `len` bits initialized to `false`. + pub fn new(len: usize) -> Self { + let words_required = len.div_ceil(BITS_PER_WORD); + Bitset { + words: vec![0; words_required], + len, + } + } + + /// Returns the total number of bits. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Returns `true` if the bitset contains zero bits. + #[cfg(test)] + #[inline] + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + #[inline(always)] + fn get_word_and_mask(index: usize) -> (usize, u64) { + let word_index = index / BITS_PER_WORD; + let bit_mask = 1u64 << (index % BITS_PER_WORD); + (word_index, bit_mask) + } + + /// Returns the bit value at `index`. + #[inline] + pub fn get(&self, index: usize) -> bool { + debug_assert!(index < self.len); + let (word_index, mask) = Bitset::get_word_and_mask(index); + (self.words[word_index] & mask) != 0 + } + + /// Sets the bit at `index` to `1` (true). + #[inline] + pub fn set(&mut self, index: usize) { + debug_assert!(index < self.len); + let (word_index, mask) = Bitset::get_word_and_mask(index); + self.words[word_index] |= mask; + } + + /// Clears the bit at `index` to `0` (false). + #[inline] + pub fn clear(&mut self, index: usize) { + debug_assert!(index < self.len); + let (word_index, mask) = Bitset::get_word_and_mask(index); + self.words[word_index] &= !mask; + } + + /// Sets all bits in `range` to `1` (true). + pub fn set_range(&mut self, range: std::ops::Range) { + debug_assert!(range.end <= self.len); + for i in range { + self.set(i); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_bitset_empty() { + let bs = Bitset::new(0); + assert_eq!(bs.len(), 0); + assert!(bs.is_empty()); + assert_eq!(bs.words.len(), 0); + } + + #[test] + fn test_bitset_set_and_get() { + let mut bs = Bitset::new(130); + assert_eq!(bs.len(), 130); + assert_eq!(bs.words.len(), 3); // 130 / 64 rounded up is 3 + + // Initially all bits are false + for i in 0..130 { + assert!(!bs.get(i)); + } + + // Set boundary bits: 0, 63, 64, 127, 129 + bs.set(0); + bs.set(63); + bs.set(64); + bs.set(127); + bs.set(129); + + assert!(bs.get(0)); + assert!(bs.get(63)); + assert!(bs.get(64)); + assert!(bs.get(127)); + assert!(bs.get(129)); + + // Neighboring bits must remain false + assert!(!bs.get(1)); + assert!(!bs.get(62)); + assert!(!bs.get(65)); + assert!(!bs.get(126)); + assert!(!bs.get(128)); + } + + #[test] + fn test_bitset_clear() { + let mut bs = Bitset::new(100); + bs.set(42); + assert!(bs.get(42)); + + bs.clear(42); + assert!(!bs.get(42)); + } + + #[test] + fn test_bitset_set_range() { + let mut bs = Bitset::new(200); + + // Empty range does nothing + bs.set_range(10..10); + assert!(!bs.get(10)); + bs.set_range(0..0); + + // Range within single word + bs.set_range(5..10); + for i in 0..200 { + assert_eq!(bs.get(i), (5..10).contains(&i)); + } + + // Cross word boundary (64) + bs.set_range(60..70); + for i in 5..10 { + assert!(bs.get(i)); + } + for i in 60..70 { + assert!(bs.get(i)); + } + assert!(!bs.get(59)); + assert!(!bs.get(70)); + + // Exact single word (64..128) + bs.set_range(64..128); + for i in 64..128 { + assert!(bs.get(i)); + } + + // Spanning across multiple words (10..150) + let mut bs2 = Bitset::new(200); + bs2.set_range(10..150); + for i in 0..200 { + assert_eq!(bs2.get(i), (10..150).contains(&i)); + } + } + + #[test] + fn test_bitset_clone_and_eq() { + let mut bs1 = Bitset::new(70); + bs1.set(10); + bs1.set(65); + + let bs2 = bs1.clone(); + assert_eq!(bs1, bs2); + + let mut bs3 = bs1.clone(); + bs3.set(11); + assert_ne!(bs1, bs3); + } + + #[test] + fn test_bitset_words_allocation() { + assert_eq!(Bitset::new(0).words.len(), 0); + assert_eq!(Bitset::new(1).words.len(), 1); + assert_eq!(Bitset::new(63).words.len(), 1); + assert_eq!(Bitset::new(64).words.len(), 1); + assert_eq!(Bitset::new(65).words.len(), 2); + assert_eq!(Bitset::new(128).words.len(), 2); + assert_eq!(Bitset::new(129).words.len(), 3); + assert_eq!(Bitset::new(100_000).words.len(), 1563); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic] + fn test_bitset_get_out_of_bounds() { + let bs = Bitset::new(10); + let _ = bs.get(10); + } + + #[test] + #[cfg(debug_assertions)] + #[should_panic] + fn test_bitset_set_out_of_bounds() { + let mut bs = Bitset::new(10); + bs.set(10); + } +} diff --git a/src/ses/optimize/fxhasher.rs b/src/ses/optimize/fxhasher.rs new file mode 100644 index 00000000..42dd098c --- /dev/null +++ b/src/ses/optimize/fxhasher.rs @@ -0,0 +1,281 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +//! Fast, non-cryptographic hashing for internal token interning. +//! +//! Derived from `rustc-hash` v2 (`Apache-2.0 OR MIT`, Orson Peters / The Rust Project Developers): +//! polynomial `usize` accumulation paired with a wyhash-inspired byte-slice compressor +//! (`hash_bytes`) and bit-rotation finalizer tailored for `std::collections::HashMap` (`hashbrown`). +//! +//! Do NOT use for HashDoS-sensitive untrusted public hash tables; `TokenInterner` always verifies +//! collisions via full byte-slice equality. + +use core::hash::{BuildHasher, Hasher}; + +#[cfg(target_pointer_width = "64")] +const K: usize = 0xf135_7aea_2e62_a9c5; +#[cfg(target_pointer_width = "32")] +const K: usize = 0x93d7_65dd; + +const SEED1: u64 = 0x243f_6a88_85a3_08d3; +const SEED2: u64 = 0x1319_8a2e_0370_7344; +const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa409_3822_299f_31d0; + +/// Type alias for a `std::collections::HashMap` using the in-tree [`FxBuildHasher`]. +pub(crate) type FxHashMap = std::collections::HashMap; + +/// A `BuildHasher` constructing default [`FxHasher`] instances. +#[derive(Copy, Clone, Default)] +pub(crate) struct FxBuildHasher; + +impl BuildHasher for FxBuildHasher { + type Hasher = FxHasher; + + #[inline] + fn build_hasher(&self) -> FxHasher { + FxHasher::new() + } +} + +/// Non-cryptographic, high-throughput `Hasher` for short keys and byte slices. +#[derive(Clone, Default)] +pub(crate) struct FxHasher { + hash: usize, +} + +impl FxHasher { + /// Creates a new `FxHasher` initialized with seed `0`. + #[inline] + pub(crate) const fn new() -> Self { + Self { hash: 0 } + } + + /// Creates a new `FxHasher` initialized with a custom `seed`. + #[cfg(test)] + #[inline] + pub(crate) const fn with_seed(seed: usize) -> Self { + Self { hash: seed } + } + + #[inline] + fn add_to_hash(&mut self, i: usize) { + self.hash = self.hash.wrapping_add(i).wrapping_mul(K); + } +} + +impl Hasher for FxHasher { + #[inline] + fn write(&mut self, bytes: &[u8]) { + self.write_u64(hash_bytes(bytes)); + } + + #[inline] + fn write_u8(&mut self, i: u8) { + self.add_to_hash(i as usize); + } + + #[inline] + fn write_u16(&mut self, i: u16) { + self.add_to_hash(i as usize); + } + + #[inline] + fn write_u32(&mut self, i: u32) { + self.add_to_hash(i as usize); + } + + #[inline] + fn write_u64(&mut self, i: u64) { + self.add_to_hash(i as usize); + #[cfg(target_pointer_width = "32")] + self.add_to_hash((i >> 32) as usize); + } + + #[inline] + fn write_u128(&mut self, i: u128) { + self.add_to_hash(i as usize); + #[cfg(target_pointer_width = "32")] + self.add_to_hash((i >> 32) as usize); + self.add_to_hash((i >> 64) as usize); + #[cfg(target_pointer_width = "32")] + self.add_to_hash((i >> 96) as usize); + } + + #[inline] + fn write_usize(&mut self, i: usize) { + self.add_to_hash(i); + } + + #[inline] + fn finish(&self) -> u64 { + #[cfg(target_pointer_width = "64")] + const ROTATE: u32 = 26; + #[cfg(target_pointer_width = "32")] + const ROTATE: u32 = 15; + + // Rotate high-entropy MSB bits down for bucket indexing while keeping + // strong entropy in the upper 7 bits used by `hashbrown` SIMD control bytes. + self.hash.rotate_left(ROTATE) as u64 + } +} + +#[inline] +fn multiply_mix(x: u64, y: u64) -> u64 { + if cfg!(any( + all( + target_pointer_width = "64", + not(any(target_arch = "sparc64", target_arch = "wasm64")), + ), + target_arch = "aarch64", + target_arch = "x86_64", + all(target_family = "wasm", target_feature = "wide-arithmetic"), + )) { + let full = (x as u128).wrapping_mul(y as u128); + let lo = full as u64; + let hi = (full >> 64) as u64; + lo ^ hi + } else { + let lx = x as u32; + let ly = y as u32; + let hx = (x >> 32) as u32; + let hy = (y >> 32) as u32; + + let afull = (lx as u64).wrapping_mul(hy as u64); + let bfull = (hx as u64).wrapping_mul(ly as u64); + afull ^ bfull.rotate_right(32) + } +} + +#[inline] +fn hash_bytes(bytes: &[u8]) -> u64 { + let len = bytes.len(); + let mut s0 = SEED1; + let mut s1 = SEED2; + + if len <= 16 { + if len >= 8 { + s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap()); + s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap()); + } else if len >= 4 { + s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64; + s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64; + } else if len > 0 { + let lo = bytes[0]; + let mid = bytes[len / 2]; + let hi = bytes[len - 1]; + s0 ^= lo as u64; + s1 ^= ((hi as u64) << 8) | mid as u64; + } + } else { + // Iterate up to `len - 1` so exact multiples of 16 do not hash the final + // 16 bytes twice when mixing the overlapping suffix below. + let mut bulk = &bytes[..(len - 1)]; + while let Some((chunk, rest)) = bulk.split_first_chunk::<16>() { + let x = u64::from_le_bytes(chunk[..8].try_into().unwrap()); + let y = u64::from_le_bytes(chunk[8..].try_into().unwrap()); + + let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y); + s0 = s1; + s1 = t; + bulk = rest; + } + + let suffix = &bytes[len - 16..]; + s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap()); + s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap()); + } + + multiply_mix(s0, s1) ^ (len as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + use core::hash::{BuildHasher, Hash, Hasher}; + + fn hash_bytes_raw(bytes: &[u8]) -> u64 { + let mut hasher = FxHasher::new(); + hasher.write(bytes); + hasher.finish() + } + + #[test] + fn test_fxhash_determinism_and_integers() { + assert_eq!(FxBuildHasher.hash_one(0_u64), 0); + assert_ne!(FxBuildHasher.hash_one(1_u64), 0); + assert_ne!(FxBuildHasher.hash_one(1_u64), FxBuildHasher.hash_one(2_u64)); + assert_ne!( + FxBuildHasher.hash_one(u32::MAX), + FxBuildHasher.hash_one(u32::MAX - 1) + ); + assert_ne!( + FxBuildHasher.hash_one(1_u128), + FxBuildHasher.hash_one(1_u128 << 64) + ); + } + + #[test] + fn test_fxhash_all_length_tiers_and_boundaries() { + // Test every boundary transition in hash_bytes: + // 0, 1..=3, 4..=7, 8..=16, 17..32 (16-byte chunks), exact multiples (16, 32, 48). + let lengths = [ + 0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 24, 31, 32, 33, 48, 64, + ]; + let mut hashes = Vec::with_capacity(lengths.len()); + for &len in &lengths { + let buf: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31)).collect(); + let h = hash_bytes_raw(&buf); + assert_eq!( + h, + hash_bytes_raw(&buf), + "non-deterministic hash for len {len}" + ); + assert!(!hashes.contains(&h), "unexpected collision at len {len}"); + hashes.push(h); + } + } + + #[test] + fn test_fxhash_zero_inputs_do_not_collapse() { + // Zeroed byte slices of distinct lengths must stay distinct. + let z0 = hash_bytes_raw(&[]); + let z1 = hash_bytes_raw(&[0]); + let z8 = hash_bytes_raw(&[0; 8]); + let z16 = hash_bytes_raw(&[0; 16]); + let z32 = hash_bytes_raw(&[0; 32]); + let set = [z0, z1, z8, z16, z32]; + for i in 0..set.len() { + for j in (i + 1)..set.len() { + assert_ne!(set[i], set[j], "zero collapse between index {i} and {j}"); + } + } + } + + #[test] + fn test_fxhash_single_bit_and_position_sensitivity() { + for len in [1_usize, 4, 8, 12, 16, 24, 40] { + let base = vec![0x5Au8; len]; + let base_hash = hash_bytes_raw(&base); + for pos in 0..len { + let mut mutated = base.clone(); + mutated[pos] ^= 0x01; + assert_ne!( + base_hash, + hash_bytes_raw(&mutated), + "single-bit flip at pos {pos} (len {len}) collided" + ); + } + } + } + + #[test] + fn test_fxhash_with_seed_differs() { + let mut a = FxHasher::with_seed(1); + let mut b = FxHasher::with_seed(2); + "hello".hash(&mut a); + "hello".hash(&mut b); + assert_ne!(a.finish(), b.finish()); + } +} diff --git a/src/ses/optimize/intern.rs b/src/ses/optimize/intern.rs new file mode 100644 index 00000000..43d65666 --- /dev/null +++ b/src/ses/optimize/intern.rs @@ -0,0 +1,166 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +use crate::ses::optimize::fxhasher::{FxBuildHasher, FxHashMap}; +use core::hash::{Hash, Hasher}; + +/// Internal key wrapper whose `Hash` implementation writes slice bytes directly, +/// avoiding `std`'s extra `write_usize(len)` prefix call since [`crate::ses::optimize::fxhasher::FxHasher`] +/// already mixes the slice length inside `hash_bytes`. This is just a small micro-optimization. +#[derive(Eq, PartialEq)] +struct LineKey<'a>(&'a [u8]); + +impl Hash for LineKey<'_> { + #[inline] + fn hash(&self, state: &mut H) { + state.write(self.0); + } +} + +/// Maps arbitrary byte sequences to unique `u32` token IDs. +/// +/// Uses [`FxHashMap`] for fast, non-cryptographic hashing of short byte slices +/// (such as source code lines), avoiding the latency of standard cryptographic hashing +/// while guaranteeing sound equality checks without hash collisions. +pub(crate) struct TokenInterner<'a> { + map: FxHashMap, u32>, +} + +impl<'a> TokenInterner<'a> { + /// Creates a new `TokenInterner` with pre-allocated capacity for `capacity` unique tokens, + /// eliminating dynamic table reallocations and rehashing. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Self { + map: FxHashMap::with_capacity_and_hasher(capacity, FxBuildHasher), + } + } + + /// Interns a slice of tokens implementing `AsRef<[u8]>` into a `Vec`, mapping identical + /// tokens to matching incremental `u32` IDs. + pub fn intern>(&mut self, tokens: &'a [T]) -> Vec { + let mut ids = Vec::with_capacity(tokens.len()); + for tok in tokens { + let bytes: &'a [u8] = tok.as_ref(); + let next_id = self.map.len() as u32; + let key = LineKey(bytes); + let id = *self.map.entry(key).or_insert(next_id); + ids.push(id); + } + ids + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_interner() { + let tokens = ["apple", "banana", "apple", "cherry"]; + let mut interner = TokenInterner::with_capacity(tokens.len()); + let ids = interner.intern(&tokens); + + assert_eq!(ids.len(), 4); + assert_eq!(ids[0], ids[2]); // "apple" == "apple" + assert_ne!(ids[0], ids[1]); // "apple" != "banana" + assert_ne!(ids[1], ids[3]); // "banana" != "cherry" + } + + #[test] + fn test_interner_raw_bytes() { + let tokens: [&[u8]; 4] = [b"apple", b"banana", b"apple", b"cherry"]; + let mut interner = TokenInterner::with_capacity(tokens.len()); + let ids = interner.intern(&tokens); + + assert_eq!(ids.len(), 4); + assert_eq!(ids[0], ids[2]); // b"apple" == b"apple" + assert_ne!(ids[0], ids[1]); // b"apple" != b"banana" + assert_ne!(ids[1], ids[3]); // b"banana" != b"cherry" + } + + #[test] + fn test_interner_empty_and_zero_capacity() { + let mut interner = TokenInterner::with_capacity(0); + let empty_tokens: [&str; 0] = []; + let ids = interner.intern(&empty_tokens); + assert!(ids.is_empty()); + + // Intern empty strings/bytes + let empty_str = ["", ""]; + let ids2 = interner.intern(&empty_str); + assert_eq!(ids2.len(), 2); + assert_eq!(ids2[0], ids2[1]); + } + + #[test] + fn test_interner_chunk_boundary_differences() { + let mut interner = TokenInterner::with_capacity(16); + // Vary lengths around 8-byte word boundaries: 7, 8, 9, 15, 16, 17 bytes + let tokens = [ + &b"1234567"[..], + &b"1234568"[..], // differs at 7th byte + &b"12345678"[..], // 8 bytes + &b"12345679"[..], // 8 bytes, differs at 8th byte + &b"123456789"[..], // 9 bytes + &b"123456780"[..], // 9 bytes, differs at 9th byte + &b"123456781234567"[..], // 15 bytes + &b"1234567812345678"[..], // 16 bytes + &b"1234567812345679"[..], // 16 bytes, differs at last byte + &b"12345678123456780"[..], // 17 bytes + ]; + let ids = interner.intern(&tokens); + assert_eq!(ids.len(), 10); + // All these must have distinct IDs + for i in 0..ids.len() { + for j in (i + 1)..ids.len() { + assert_ne!(ids[i], ids[j], "token {} and {} had collision", i, j); + } + } + } + + #[test] + fn test_interner_incremental_batches() { + let mut interner = TokenInterner::with_capacity(4); + let batch1 = ["alpha", "beta"]; + let ids1 = interner.intern(&batch1); + + let batch2 = ["gamma", "alpha", "beta", "delta"]; + let ids2 = interner.intern(&batch2); + + assert_eq!(ids1[0], ids2[1]); // "alpha" + assert_eq!(ids1[1], ids2[2]); // "beta" + assert_ne!(ids2[0], ids1[0]); // "gamma" is new + assert_ne!(ids2[3], ids1[0]); // "delta" is new + } + + #[test] + fn test_interner_long_byte_lines() { + let mut interner = TokenInterner::with_capacity(4); + let long1 = vec![b'x'; 2000]; + let mut long2 = vec![b'x'; 2000]; + long2[1999] = b'y'; // differs at byte 1999 + + let tokens = [long1.as_slice(), long2.as_slice(), long1.as_slice()]; + let ids = interner.intern(&tokens); + + assert_eq!(ids.len(), 3); + assert_eq!(ids[0], ids[2]); + assert_ne!(ids[0], ids[1]); + } + + #[test] + fn test_interner_trailing_nul_and_length_distinctness() { + let mut interner = TokenInterner::with_capacity(8); + let tokens: [&[u8]; 5] = [b"", b"\0", b"\0\0", b"line", b"line\0"]; + let ids = interner.intern(&tokens); + assert_eq!(ids.len(), 5); + for i in 0..ids.len() { + for j in (i + 1)..ids.len() { + assert_ne!(ids[i], ids[j], "index {i} and {j} unexpectedly matched"); + } + } + } +} diff --git a/src/ses/optimize/mod.rs b/src/ses/optimize/mod.rs new file mode 100644 index 00000000..676c430f --- /dev/null +++ b/src/ses/optimize/mod.rs @@ -0,0 +1,9 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +pub(crate) mod bitset; +pub(crate) mod fxhasher; +pub(crate) mod intern; +pub(crate) mod trim; diff --git a/src/ses/optimize/trim.rs b/src/ses/optimize/trim.rs new file mode 100644 index 00000000..804bea11 --- /dev/null +++ b/src/ses/optimize/trim.rs @@ -0,0 +1,80 @@ +// This file is part of the uutils diffutils package. +// +// For the full copyright and license information, please view the LICENSE-* +// files that was distributed with this source code. + +/// Stores the results of common prefix and suffix stripping. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Trimmed<'a, T> { + pub prefix_len: usize, + pub suffix_len: usize, + pub slice_a: &'a [T], + pub slice_b: &'a [T], +} + +/// Strips common prefix and suffix elements in `O(N)` time before running the Myers engine. +pub(crate) fn trim_slices<'a, T, F>(a: &'a [T], b: &'a [T], mut equals: F) -> Trimmed<'a, T> +where + F: FnMut(&T, &T) -> bool, +{ + let mut prefix_len = 0; + while prefix_len < a.len() && prefix_len < b.len() && equals(&a[prefix_len], &b[prefix_len]) { + prefix_len += 1; + } + + let mut suffix_len = 0; + while suffix_len < (a.len() - prefix_len) + && suffix_len < (b.len() - prefix_len) + && equals(&a[a.len() - 1 - suffix_len], &b[b.len() - 1 - suffix_len]) + { + suffix_len += 1; + } + + Trimmed { + prefix_len, + suffix_len, + slice_a: &a[prefix_len..a.len() - suffix_len], + slice_b: &b[prefix_len..b.len() - suffix_len], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_trim_slices() { + let a = ["header", "a", "footer"]; + let b = ["header", "b", "footer"]; + let trimmed = trim_slices(&a, &b, |x, y| x == y); + + assert_eq!(trimmed.prefix_len, 1); + assert_eq!(trimmed.suffix_len, 1); + assert_eq!(trimmed.slice_a, &["a"]); + assert_eq!(trimmed.slice_b, &["b"]); + } + + #[test] + fn test_trim_identical() { + let a = ["header", "body", "footer"]; + let b = ["header", "body", "footer"]; + let trimmed = trim_slices(&a, &b, |x, y| x == y); + + assert_eq!(trimmed.prefix_len, 3); + assert_eq!(trimmed.suffix_len, 0); + assert!(trimmed.slice_a.is_empty()); + assert!(trimmed.slice_b.is_empty()); + } + + #[test] + fn test_trim_disjoint() { + let a = ["1", "2"]; + let b = ["3", "4"]; + let trimmed = trim_slices(&a, &b, |x, y| x == y); + + assert_eq!(trimmed.prefix_len, 0); + assert_eq!(trimmed.suffix_len, 0); + assert_eq!(trimmed.slice_a, &["1", "2"]); + assert_eq!(trimmed.slice_b, &["3", "4"]); + } +} diff --git a/src/side_diff.rs b/src/side_diff.rs index 9c0fbe06..18907ac5 100644 --- a/src/side_diff.rs +++ b/src/side_diff.rs @@ -4,11 +4,11 @@ // 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; use crate::params::Params; +use crate::ses; use crate::utils::comparison_lines_inclusive; const GUTTER_WIDTH_MIN: usize = 3; @@ -351,14 +351,18 @@ 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.raw, b"", b'<', output, &config).unwrap(), - Result::Right(right_ln) => { - push_output(b"", right_ln.raw, b'>', output, &config).unwrap() + 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() } - Result::Both(left_ln, right_ln) => { - push_output(left_ln.raw, right_ln.raw, 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 f09036fc..1eae525d 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -7,8 +7,11 @@ use std::collections::VecDeque; use std::io::Write; use crate::params::Params; -use crate::utils::{comparison_lines, do_write_line, line_prefix}; -use crate::utils::{get_modification_time, write_file_header, FunctionLineFinder, TimestampStyle}; +use crate::ses; +use crate::utils::{ + comparison_lines, do_write_line, get_modification_time, line_prefix, write_file_header, + FunctionLineFinder, TimestampStyle, +}; #[derive(Debug, PartialEq)] pub enum DiffLine { @@ -87,9 +90,10 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> 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) => { + ses::Change::Delete(str) => { if lines_since_mismatch > max_gap { results.push(mismatch); mismatch = Mismatch::new( @@ -107,7 +111,7 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { 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 +132,7 @@ fn make_diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { 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/utils.rs b/src/utils.rs index 6d6d1395..396acac8 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -159,6 +159,12 @@ impl<'a> std::ops::Deref for ComparisonLine<'a> { } } +impl<'a> AsRef<[u8]> for ComparisonLine<'a> { + fn as_ref(&self) -> &[u8] { + &self.key + } +} + impl<'a> PartialEq for ComparisonLine<'a> { fn eq(&self, other: &Self) -> bool { self.key == other.key diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 2955704d..3ed3cecc 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -1200,6 +1200,248 @@ fn label_errors(#[case] args: &[&str], #[case] error: &str) { .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"); +} + #[test] fn width_option_forms() { let (at, ts) = at_and_ts!();