Skip to main content

vtcode_commons/
line_blocks.rs

1//! Line-block containment for deduplicating tool output streams.
2//!
3//! Multiple renderers need to know whether one stream's text already appears
4//! inside another (merged `output` vs named `stdout`/`stderr`) so each line is
5//! shown once. This module is the single home; the runloop pipe-stream
6//! canonicalizer and the lifecycle summary aggregator used to carry verbatim
7//! copies and now delegate here.
8
9/// Ranges (line offsets) where `candidate` occurs in `container_lines` as a
10/// contiguous block, in ascending order. Empty when `candidate` is empty or
11/// longer than the container.
12fn block_ranges_in(container_lines: &[&str], candidate: &str) -> Vec<(usize, usize)> {
13    let candidate_lines = candidate.lines().collect::<Vec<_>>();
14    if candidate_lines.is_empty() || candidate_lines.len() > container_lines.len() {
15        return Vec::new();
16    }
17
18    container_lines
19        .windows(candidate_lines.len())
20        .enumerate()
21        .filter_map(|(start, window)| {
22            (window == candidate_lines.as_slice()).then_some((start, start + candidate_lines.len()))
23        })
24        .collect()
25}
26
27/// True when `candidate` occurs in `container` as a contiguous line block.
28///
29/// Short-circuits on the first match: unlike collecting ranges and testing
30/// emptiness, this builds no ranges vector and stops scanning early. An empty
31/// candidate matches nothing.
32#[must_use]
33pub fn contains_line_block(container: &str, candidate: &str) -> bool {
34    let container_lines = container.lines().collect::<Vec<_>>();
35    let candidate_lines = candidate.lines().collect::<Vec<_>>();
36    if candidate_lines.is_empty() || candidate_lines.len() > container_lines.len() {
37        return false;
38    }
39
40    container_lines
41        .windows(candidate_lines.len())
42        .any(|window| window == candidate_lines.as_slice())
43}
44
45/// True when `first` and `second` both occur in `container` in non-overlapping
46/// ranges. Requiring distinct blocks matters when the streams are identical or
47/// one is a prefix of the other: a single occurrence cannot prove both are
48/// copies. The container lines are collected once for both scans.
49#[must_use]
50pub fn contains_distinct_line_blocks(container: &str, first: &str, second: &str) -> bool {
51    let container_lines = container.lines().collect::<Vec<_>>();
52    let first_ranges = block_ranges_in(&container_lines, first);
53    let second_ranges = block_ranges_in(&container_lines, second);
54    first_ranges.iter().any(|&(first_start, first_end)| {
55        second_ranges
56            .iter()
57            .any(|&(second_start, second_end)| first_end <= second_start || second_end <= first_start)
58    })
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn contains_finds_middle_block_but_not_absent_text() {
67        let container = "alpha\nbeta\ngamma\ndelta";
68        assert!(contains_line_block(container, "beta\ngamma"));
69        assert!(!contains_line_block(container, "beta\ndelta"));
70    }
71
72    #[test]
73    fn contains_is_directional_for_prefix_pairs() {
74        // Asymmetric oracle: a prefix is contained in the whole, never the reverse.
75        assert!(contains_line_block("one\ntwo\nthree", "one\ntwo"));
76        assert!(!contains_line_block("one\ntwo", "one\ntwo\nthree"));
77    }
78
79    #[test]
80    fn contains_rejects_empty_and_oversized_candidates() {
81        assert!(!contains_line_block("one\ntwo", ""));
82        assert!(!contains_line_block("", "one"));
83        assert!(!contains_line_block("", ""));
84        assert!(!contains_line_block("one", "one\ntwo"));
85    }
86
87    #[test]
88    fn contains_matches_exact_and_single_line_candidates() {
89        assert!(contains_line_block("one\ntwo", "one\ntwo"));
90        assert!(contains_line_block("one\ntwo\nthree", "two"));
91        assert!(!contains_line_block("one\ntwo\nthree", "four"));
92    }
93
94    #[test]
95    fn contains_ignores_trailing_newline_differences() {
96        // `str::lines` strips terminators on both sides, so trailing newlines
97        // never affect the comparison either way.
98        assert!(contains_line_block("one\ntwo\n", "one\ntwo"));
99        assert!(contains_line_block("one\ntwo", "one\ntwo\n"));
100    }
101
102    #[test]
103    fn distinct_blocks_reject_a_single_shared_occurrence() {
104        // Identical streams with one occurrence: one block cannot prove both.
105        let container = "out\nerr";
106        assert!(!contains_distinct_line_blocks(container, "out\nerr", "out\nerr"));
107        // Same when one candidate is a prefix of the other over one occurrence.
108        assert!(!contains_distinct_line_blocks(container, "out\nerr", "out"));
109    }
110
111    #[test]
112    fn distinct_blocks_accept_separate_occurrences() {
113        let container = "out-1\nerr-1\nout-2\nerr-2";
114        assert!(contains_distinct_line_blocks(container, "out-1\nerr-1", "out-2\nerr-2"));
115        // Order of the two candidates does not matter.
116        assert!(contains_distinct_line_blocks(container, "out-2\nerr-2", "out-1\nerr-1"));
117    }
118
119    #[test]
120    fn distinct_blocks_reject_missing_candidates() {
121        let container = "out\nerr";
122        assert!(!contains_distinct_line_blocks(container, "out", "absent"));
123        assert!(!contains_distinct_line_blocks(container, "absent", "err"));
124        assert!(!contains_distinct_line_blocks(container, "", "err"));
125    }
126
127    #[test]
128    fn block_ranges_report_every_occurrence_in_order() {
129        let container_lines = ["a", "b", "a", "b", "c"];
130        assert_eq!(block_ranges_in(&container_lines, "a\nb"), vec![(0, 2), (2, 4)]);
131        assert_eq!(block_ranges_in(&container_lines, "b\nc"), vec![(3, 5)]);
132        assert!(block_ranges_in(&container_lines, "c\na").is_empty());
133        assert!(block_ranges_in(&container_lines, "").is_empty());
134        assert!(block_ranges_in(&[], "a").is_empty());
135    }
136}