From 3a938ae1d3a0923a483ece68aecbed2a8052865a Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 28 Jul 2022 15:14:54 +0200 Subject: [PATCH] Raise an explicit panic when context_lines is 0. Fixes #37 --- src/common.rs | 2 ++ src/text/mod.rs | 9 +++++++++ src/udiff.rs | 3 ++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/common.rs b/src/common.rs index 40d1ae7..7adfa11 100644 --- a/src/common.rs +++ b/src/common.rs @@ -101,6 +101,8 @@ pub fn get_diff_ratio(ops: &[DiffOp], old_len: usize, new_len: usize) -> f32 { /// This will leave holes behind in long periods of equal ranges so that /// you can build things like unified diffs. pub fn group_diff_ops(mut ops: Vec, n: usize) -> Vec> { + assert!(n > 0, "n must be 1 or larger"); + if ops.is_empty() { return vec![]; } diff --git a/src/text/mod.rs b/src/text/mod.rs index dbad62b..bdc75a0 100644 --- a/src/text/mod.rs +++ b/src/text/mod.rs @@ -758,3 +758,12 @@ fn test_serde_ops() { let json = serde_json::to_string_pretty(&changes).unwrap(); insta::assert_snapshot!(&json); } + +#[test] +#[should_panic = "n must be 1 or larger"] +fn test_regression_issue_37() { + let config = TextDiffConfig::default(); + let diff = config.diff_lines("", ""); + let mut output = diff.unified_diff(); + output.context_radius(0).to_string(); +} diff --git a/src/udiff.rs b/src/udiff.rs index 80a30cf..d975068 100644 --- a/src/udiff.rs +++ b/src/udiff.rs @@ -139,7 +139,8 @@ impl<'diff, 'old, 'new, 'bufs, T: DiffableStr + ?Sized> UnifiedDiff<'diff, 'old, /// Changes the context radius. /// /// The context radius is the number of lines between changes that should - /// be emitted. This defaults to `3`. + /// be emitted. This defaults to `3`. This value must be one or larger or + /// creating the diff will panic. pub fn context_radius(&mut self, n: usize) -> &mut Self { self.context_radius = n; self