From 679c32ddeeab1c649d0c23fdf2bc164d9cc663d7 Mon Sep 17 00:00:00 2001 From: alexjg Date: Mon, 14 Nov 2022 20:39:48 +0000 Subject: [PATCH] check for identical sequences in lcs to avoid overflow panic (#43) --- src/algorithms/lcs.rs | 16 ++++++++++++++++ .../similar__algorithms__lcs__same.snap | 12 ++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 src/algorithms/snapshots/similar__algorithms__lcs__same.snap diff --git a/src/algorithms/lcs.rs b/src/algorithms/lcs.rs index 6d1af68..5eb3a63 100644 --- a/src/algorithms/lcs.rs +++ b/src/algorithms/lcs.rs @@ -64,6 +64,12 @@ where let common_prefix_len = common_prefix_len(old, old_range.clone(), new, new_range.clone()); let common_suffix_len = common_suffix_len(old, old_range.clone(), new, new_range.clone()); + // If the sequences are not different then we're done + if common_prefix_len == old_range.len() && (old_range.len() == new_range.len()) { + d.equal(0, 0, old_range.len())?; + return Ok(()); + } + let maybe_table = make_table( old, common_prefix_len..(old_range.len() - common_suffix_len), @@ -218,3 +224,13 @@ fn test_pat() { diff(&mut d, a, 0..a.len(), b, 0..b.len()).unwrap(); insta::assert_debug_snapshot!(d.ops()); } + +#[test] +fn test_same() { + let a: &[usize] = &[0, 1, 2, 3, 4, 4, 4, 5]; + let b: &[usize] = &[0, 1, 2, 3, 4, 4, 4, 5]; + + let mut d = crate::algorithms::Capture::new(); + diff(&mut d, a, 0..a.len(), b, 0..b.len()).unwrap(); + insta::assert_debug_snapshot!(d.ops()); +} diff --git a/src/algorithms/snapshots/similar__algorithms__lcs__same.snap b/src/algorithms/snapshots/similar__algorithms__lcs__same.snap new file mode 100644 index 0000000..4b9511b --- /dev/null +++ b/src/algorithms/snapshots/similar__algorithms__lcs__same.snap @@ -0,0 +1,12 @@ +--- +source: src/algorithms/lcs.rs +assertion_line: 235 +expression: d.ops() +--- +[ + Equal { + old_index: 0, + new_index: 0, + len: 8, + }, +]