Skip to main content

vtcode_commons/
preview.rs

1#![expect(
2    clippy::indexing_slicing,
3    clippy::string_slice,
4    reason = "Preview counts and UTF-8 offsets are computed from source lengths and boundary helpers."
5)]
6
7//! Shared preview formatting helpers.
8
9use crate::display_width::char_display_width_or;
10pub use crate::display_width::display_width;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub struct HeadTailPreview<'a, T> {
14    pub head: &'a [T],
15    pub tail: &'a [T],
16    pub hidden_count: usize,
17    total: usize,
18}
19
20#[derive(Clone, Debug, Eq, PartialEq)]
21pub struct TextLineExcerpt<'a> {
22    pub head: Vec<&'a str>,
23    pub tail: Vec<&'a str>,
24    pub hidden_count: usize,
25    pub total: usize,
26}
27
28pub fn truncate_to_display_width(text: &str, max_width: usize) -> &str {
29    if max_width == 0 {
30        return "";
31    }
32    if display_width(text) <= max_width {
33        return text;
34    }
35
36    let mut consumed_width = 0usize;
37    for (idx, ch) in text.char_indices() {
38        let char_width = char_display_width_or(ch, 0);
39        if consumed_width + char_width > max_width {
40            return &text[..idx];
41        }
42        consumed_width += char_width;
43    }
44
45    text
46}
47
48pub fn truncate_with_ellipsis(text: &str, max_width: usize, ellipsis: &str) -> String {
49    if max_width == 0 {
50        return String::new();
51    }
52    if display_width(text) <= max_width {
53        return text.to_string();
54    }
55
56    let ellipsis_width = display_width(ellipsis);
57    if ellipsis_width >= max_width {
58        return truncate_to_display_width(ellipsis, max_width).to_string();
59    }
60
61    let truncated = truncate_to_display_width(text, max_width - ellipsis_width);
62    format!("{truncated}{ellipsis}")
63}
64
65pub fn pad_to_display_width(text: &str, width: usize, pad_char: char) -> String {
66    let current = display_width(text);
67    if current >= width {
68        return text.to_string();
69    }
70
71    let padding = pad_char.to_string().repeat(width - current);
72    format!("{text}{padding}")
73}
74
75pub fn suffix_for_display_width(value: &str, max_width: usize) -> &str {
76    if display_width(value) <= max_width {
77        return value;
78    }
79    if max_width == 0 {
80        return "";
81    }
82
83    let mut consumed_width = 0usize;
84    let mut start_idx = value.len();
85    for (idx, ch) in value.char_indices().rev() {
86        let char_width = char_display_width_or(ch, 0);
87        if consumed_width + char_width > max_width {
88            break;
89        }
90        consumed_width += char_width;
91        start_idx = idx;
92    }
93
94    &value[start_idx..]
95}
96
97pub fn format_hidden_lines_summary(hidden: usize) -> String {
98    if hidden == 1 {
99        "… +1 line".to_string()
100    } else {
101        format!("… +{hidden} lines")
102    }
103}
104
105fn split_head_tail_preview<'a, T>(items: &'a [T], head: usize, tail: usize) -> HeadTailPreview<'a, T> {
106    let total = items.len();
107    if total <= head.saturating_add(tail) {
108        return HeadTailPreview {
109            head: items,
110            tail: &items[total..],
111            hidden_count: 0,
112            total,
113        };
114    }
115
116    let head_count = head.min(total);
117    let tail_count = tail.min(total.saturating_sub(head_count));
118    let hidden_count = total.saturating_sub(head_count + tail_count);
119
120    HeadTailPreview {
121        head: &items[..head_count],
122        tail: &items[total - tail_count..],
123        hidden_count,
124        total,
125    }
126}
127
128pub fn split_head_tail_preview_with_limit<'a, T>(
129    items: &'a [T],
130    limit: usize,
131    preferred_head: usize,
132) -> HeadTailPreview<'a, T> {
133    if limit == 0 {
134        return HeadTailPreview {
135            head: &items[..0],
136            tail: &items[..0],
137            hidden_count: items.len(),
138            total: items.len(),
139        };
140    }
141
142    if items.len() <= limit {
143        return HeadTailPreview {
144            head: items,
145            tail: &items[items.len()..],
146            hidden_count: 0,
147            total: items.len(),
148        };
149    }
150
151    let (head, tail) = summary_window(limit, preferred_head);
152    split_head_tail_preview(items, head, tail)
153}
154
155pub fn summary_window(limit: usize, preferred_head: usize) -> (usize, usize) {
156    if limit <= 2 {
157        return (0, limit);
158    }
159
160    let head = preferred_head.min((limit - 1) / 2).max(1);
161    let tail = limit.saturating_sub(head + 1).max(1);
162    (head, tail)
163}
164
165/// Pre-allocation cap (in `&str` refs, 16 bytes each) for the excerpt probe and
166/// tail ring. Real windows are a handful of lines, so this only binds
167/// pathological caller windows; growth beyond it is driven by output the
168/// caller actually asked for, never by input size.
169const EXCERPT_PREALLOC_CAP: usize = 1024;
170
171/// Single-pass head/tail excerpt over lines: O(window) memory, independent of input size.
172///
173/// The naive form (`text.lines().collect()` then slice) materializes one `&str`
174/// per line only to drop all but the window — a transient allocation proportional
175/// to the input on every large tool output. Instead this buffers at most
176/// `fit_budget + 1` lines to detect the fit case, then streams the remainder
177/// through a tail-sized ring while counting the total.
178///
179/// Contract:
180/// - `total <= fit_budget` → `head` holds every line, `tail` is empty, `hidden_count` is 0.
181/// - otherwise → `head` holds the first `head` lines, `tail` the last `tail`
182///   lines, `hidden_count = total - head - tail`.
183///
184/// Callers must pass `head + tail <= fit_budget` so both branches agree; both
185/// public wrappers satisfy this (`excerpt_text_lines` uses `head + tail`,
186/// `excerpt_text_lines_with_limit` uses `limit >= head + tail` via `summary_window`).
187/// The obligation is executable below: a violating caller fails loud instead
188/// of silently returning a wrongly-split excerpt.
189fn head_tail_excerpt<'a>(text: &'a str, fit_budget: usize, head: usize, tail: usize) -> TextLineExcerpt<'a> {
190    debug_assert!(
191        head.saturating_add(tail) <= fit_budget,
192        "window ({head} + {tail}) must fit the fit budget ({fit_budget})"
193    );
194    let mut lines = text.lines();
195    // Probe: buffer just past the fit budget to decide fit vs. overflow.
196    // Capacity is exact for small windows and capped for huge ones; growth
197    // beyond the cap only happens when the output itself needs the lines.
198    let mut leading: Vec<&'a str> = Vec::with_capacity(fit_budget.saturating_add(1).min(EXCERPT_PREALLOC_CAP));
199    for line in lines.by_ref().take(fit_budget.saturating_add(1)) {
200        leading.push(line);
201    }
202    if leading.len() <= fit_budget {
203        let total = leading.len();
204        return TextLineExcerpt {
205            head: leading,
206            tail: Vec::new(),
207            hidden_count: 0,
208            total,
209        };
210    }
211
212    // Overflow: `total > fit_budget >= head + tail`, so the window slices are
213    // exactly `head` and `tail` lines (no `min` needed) and the ring below
214    // always fills. (`fit_budget` saturates rather than overflows; saturation
215    // implies a budget no line count can reach, so overflow is unreachable then
216    // and the arithmetic below only runs on exact sums.)
217    let mut head_vec: Vec<&'a str> = Vec::with_capacity(head.min(leading.len()));
218    head_vec.extend(leading.iter().take(head).copied());
219    // Ring invariant: `write_idx < tail` whenever the ring is full; pushes
220    // before it fills append in order, so `rotate_left(write_idx)` restores
221    // oldest-first order exactly when the ring wrapped.
222    let mut ring: Vec<&'a str> = Vec::with_capacity(tail.min(EXCERPT_PREALLOC_CAP));
223    let mut write_idx = 0usize;
224    let mut fed = 0usize;
225    let mut ring_push = |line: &'a str| {
226        if tail == 0 {
227            return;
228        }
229        if ring.len() < tail {
230            ring.push(line);
231        } else {
232            ring[write_idx] = line;
233            write_idx = (write_idx + 1) % tail;
234        }
235        fed += 1;
236    };
237    for &line in leading.iter().skip(head) {
238        ring_push(line);
239    }
240    let mut total = leading.len();
241    for line in lines {
242        ring_push(line);
243        total += 1;
244    }
245    if fed > tail {
246        ring.rotate_left(write_idx);
247    }
248    let hidden_count = total.saturating_sub(head_vec.len()).saturating_sub(ring.len());
249    TextLineExcerpt { head: head_vec, tail: ring, hidden_count, total }
250}
251
252/// First `head` and last `tail` lines of `text` in a single pass.
253///
254/// Memory is O(`head + tail`), not O(total lines): large tool outputs stream
255/// through a tail-sized ring instead of materializing every line transiently.
256pub fn excerpt_text_lines<'a>(text: &'a str, head: usize, tail: usize) -> TextLineExcerpt<'a> {
257    head_tail_excerpt(text, head.saturating_add(tail), head, tail)
258}
259
260/// [`excerpt_text_lines`] with the window derived from `summary_window`.
261///
262/// Fit is tested against `limit`, not `head + tail`: `summary_window` reserves
263/// one row for the gap marker (`head + tail == limit - 1` when `limit > 2`),
264/// so an input of exactly `limit` lines still fits whole.
265pub fn excerpt_text_lines_with_limit<'a>(text: &'a str, limit: usize, preferred_head: usize) -> TextLineExcerpt<'a> {
266    let (head, tail) = summary_window(limit, preferred_head);
267    head_tail_excerpt(text, limit, head, tail)
268}
269
270/// Last `limit` lines of `text` in a single pass.
271///
272/// Memory is O(`limit`), not O(total lines): unlike `text.lines().collect()`
273/// followed by slicing off the tail, large inputs stream through a
274/// limit-sized ring instead of materializing every line transiently.
275pub fn tail_lines(text: &str, limit: usize) -> Vec<&str> {
276    let excerpt = head_tail_excerpt(text, limit, 0, limit);
277    // Fit puts everything in `head` and overflow puts the window in `tail`;
278    // both are empty only when the input is empty or the limit is zero.
279    if excerpt.tail.is_empty() {
280        excerpt.head
281    } else {
282        excerpt.tail
283    }
284}
285
286fn format_hidden_bytes_summary(hidden: usize) -> String {
287    format!("… [{hidden} bytes omitted] …")
288}
289
290pub fn condense_text_bytes(content: &str, head_bytes: usize, tail_bytes: usize) -> String {
291    let byte_len = content.len();
292    let max_inline = head_bytes + tail_bytes;
293    if byte_len <= max_inline {
294        return content.to_string();
295    }
296
297    let head_end = content.floor_char_boundary(head_bytes);
298    let tail_start_raw = byte_len.saturating_sub(tail_bytes);
299    let tail_start = content.ceil_char_boundary(tail_start_raw);
300
301    let omitted = byte_len.saturating_sub(head_end).saturating_sub(byte_len - tail_start);
302
303    format!("{}\n\n{}\n\n{}", &content[..head_end], format_hidden_bytes_summary(omitted), &content[tail_start..])
304}
305
306/// Bound model-facing error echoes of text the caller already sent
307/// (old_str, patch context, snippets). Threshold is deliberately high:
308/// typical edit mismatches are mid-string whitespace/indent issues, so most
309/// real payloads must stay intact. Only pathological multi-KB pastes are
310/// reduced to a head/tail.
311pub fn condense_error_echo(text: &str) -> String {
312    if text.len() > 2_000 {
313        condense_text_bytes(text, 800, 800)
314    } else {
315        text.to_string()
316    }
317}
318
319pub fn tail_preview_text(content: &str, tail_bytes: usize, max_lines: usize) -> String {
320    if content.is_empty() {
321        return String::new();
322    }
323
324    let tail_start = content.ceil_char_boundary(content.len().saturating_sub(tail_bytes));
325    let tail_slice = &content[tail_start..];
326
327    let mut line_start = 0usize;
328    if max_lines > 0 {
329        let mut seen = 0usize;
330        for (idx, b) in tail_slice.as_bytes().iter().enumerate().rev() {
331            if *b == b'\n' {
332                seen += 1;
333                if seen >= max_lines {
334                    line_start = idx.saturating_add(1);
335                    break;
336                }
337            }
338        }
339    }
340
341    let preview = &tail_slice[line_start..];
342    let omitted = tail_start.saturating_add(line_start);
343    if omitted == 0 {
344        return preview.to_string();
345    }
346
347    format!("{}\n{}", format_hidden_bytes_summary(omitted), preview)
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn truncate_to_display_width_respects_wide_chars() {
356        let value = "表表表";
357        assert_eq!(truncate_to_display_width(value, 5), "表表");
358    }
359
360    #[test]
361    fn truncate_with_ellipsis_respects_width_budget() {
362        assert_eq!(truncate_with_ellipsis("abcdef", 4, "…"), "abc…");
363    }
364
365    #[test]
366    fn pad_to_display_width_handles_wide_chars() {
367        let padded = pad_to_display_width("表", 4, ' ');
368        assert_eq!(display_width(padded.as_str()), 4);
369    }
370
371    #[test]
372    fn preview_padding_credits_halfwidth_sound_marks() {
373        // The shared helper must agree with the TUI: `ガ` renders in two
374        // cells, so a width-3 budget leaves exactly one space, not two.
375        assert_eq!(pad_to_display_width("ガ", 3, ' '), "ガ ");
376        assert_eq!(truncate_to_display_width("aガ", 2), "aカ");
377    }
378
379    #[test]
380    fn preview_width_math_follows_ambiguous_width_verdict() {
381        // nextest isolates this process, so the one-time verdict override
382        // cannot affect other tests. Truncation used to strip two ambiguous
383        // glyphs here because it bypassed the TUI's CJK width table.
384        crate::terminal_capabilities::set_ambiguous_width(crate::ui_protocol::AmbiguousWidthMode::Wide);
385        assert_eq!(display_width("│││"), 6);
386        assert_eq!(truncate_to_display_width("│││", 2), "│");
387        assert_eq!(pad_to_display_width("│", 3, ' '), "│ ");
388    }
389
390    #[test]
391    fn suffix_for_display_width_preserves_tail() {
392        assert_eq!(suffix_for_display_width("hello/world.rs", 8), "world.rs");
393    }
394
395    #[test]
396    fn split_head_tail_preview_preserves_hidden_count() {
397        let items = [1, 2, 3, 4, 5, 6, 7];
398        let preview = split_head_tail_preview(&items, 2, 2);
399        assert_eq!(preview.head, &[1, 2]);
400        assert_eq!(preview.tail, &[6, 7]);
401        assert_eq!(preview.hidden_count, 3);
402        assert_eq!(preview.total, 7);
403    }
404
405    #[test]
406    fn split_head_tail_preview_keeps_short_input_intact() {
407        let items = [1, 2, 3];
408        let preview = split_head_tail_preview(&items, 2, 2);
409        assert_eq!(preview.head, &[1, 2, 3]);
410        assert!(preview.tail.is_empty());
411        assert_eq!(preview.hidden_count, 0);
412    }
413
414    #[test]
415    fn split_head_tail_preview_with_limit_preserves_total_and_gap() {
416        let items = [1, 2, 3, 4, 5, 6, 7];
417        let preview = split_head_tail_preview_with_limit(&items, 6, 3);
418        assert_eq!(preview.head, &[1, 2]);
419        assert_eq!(preview.tail, &[5, 6, 7]);
420        assert_eq!(preview.hidden_count, 2);
421        assert_eq!(preview.total, 7);
422    }
423
424    #[test]
425    fn summary_window_reserves_gap_row() {
426        assert_eq!(summary_window(6, 3), (2, 3));
427        assert_eq!(summary_window(2, 3), (0, 2));
428    }
429
430    #[test]
431    fn hidden_lines_summary_matches_existing_copy() {
432        assert_eq!(format_hidden_lines_summary(1), "… +1 line");
433        assert_eq!(format_hidden_lines_summary(4), "… +4 lines");
434    }
435
436    #[test]
437    fn excerpt_text_lines_builds_head_tail_vectors() {
438        let preview = excerpt_text_lines("l1\nl2\nl3\nl4\nl5\nl6", 2, 2);
439        assert_eq!(preview.head, vec!["l1", "l2"]);
440        assert_eq!(preview.tail, vec!["l5", "l6"]);
441        assert_eq!(preview.hidden_count, 2);
442        assert_eq!(preview.total, 6);
443    }
444
445    #[test]
446    fn excerpt_text_lines_splits_asymmetric_windows() {
447        let text = "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8";
448        let preview = excerpt_text_lines(text, 2, 3);
449        assert_eq!(preview.head, vec!["l1", "l2"]);
450        assert_eq!(preview.tail, vec!["l6", "l7", "l8"]);
451        assert_eq!(preview.hidden_count, 3);
452        assert_eq!(preview.total, 8);
453
454        // Swapped windows select the opposite ends (asymmetric oracle: a
455        // head/tail mix-up or off-by-one cannot pass both directions).
456        let swapped = excerpt_text_lines(text, 3, 2);
457        assert_eq!(swapped.head, vec!["l1", "l2", "l3"]);
458        assert_eq!(swapped.tail, vec!["l7", "l8"]);
459        assert_eq!(swapped.hidden_count, 3);
460        assert_eq!(swapped.total, 8);
461    }
462
463    #[test]
464    fn excerpt_text_lines_keeps_exact_fit_whole() {
465        // total == head + tail: everything fits, nothing hidden.
466        let fit = excerpt_text_lines("l1\nl2\nl3\nl4\nl5", 2, 3);
467        assert_eq!(fit.head, vec!["l1", "l2", "l3", "l4", "l5"]);
468        assert!(fit.tail.is_empty());
469        assert_eq!(fit.hidden_count, 0);
470        assert_eq!(fit.total, 5);
471
472        // One line past the window hides exactly one line.
473        let overflow = excerpt_text_lines("l1\nl2\nl3\nl4\nl5\nl6", 2, 3);
474        assert_eq!(overflow.head, vec!["l1", "l2"]);
475        assert_eq!(overflow.tail, vec!["l4", "l5", "l6"]);
476        assert_eq!(overflow.hidden_count, 1);
477        assert_eq!(overflow.total, 6);
478    }
479
480    #[test]
481    fn excerpt_text_lines_handles_empty_windows() {
482        let text = "l1\nl2\nl3";
483        let neither = excerpt_text_lines(text, 0, 0);
484        assert!(neither.head.is_empty());
485        assert!(neither.tail.is_empty());
486        assert_eq!(neither.hidden_count, 3);
487        assert_eq!(neither.total, 3);
488
489        let head_only = excerpt_text_lines(text, 2, 0);
490        assert_eq!(head_only.head, vec!["l1", "l2"]);
491        assert!(head_only.tail.is_empty());
492        assert_eq!(head_only.hidden_count, 1);
493
494        let tail_only = excerpt_text_lines(text, 0, 2);
495        assert!(tail_only.head.is_empty());
496        assert_eq!(tail_only.tail, vec!["l2", "l3"]);
497        assert_eq!(tail_only.hidden_count, 1);
498
499        let empty = excerpt_text_lines("", 2, 2);
500        assert!(empty.head.is_empty());
501        assert!(empty.tail.is_empty());
502        assert_eq!(empty.hidden_count, 0);
503        assert_eq!(empty.total, 0);
504    }
505
506    #[test]
507    fn excerpt_text_lines_matches_naive_slicing() {
508        // Independent re-derivation: materialize-then-slice is the pre-rewrite
509        // contract; the single-pass version must agree on every window shape,
510        // including windows larger than the input.
511        let text = (1..=50).map(|i| format!("line-{i:02}")).collect::<Vec<_>>().join("\n");
512        let all: Vec<&str> = text.lines().collect();
513        for (head, tail) in [
514            (0, 0),
515            (0, 5),
516            (5, 0),
517            (1, 1),
518            (3, 7),
519            (7, 3),
520            (25, 25),
521            (49, 49),
522            (50, 50),
523            (100, 100),
524        ] {
525            let preview = excerpt_text_lines(&text, head, tail);
526            let total = all.len();
527            let (expected_head, expected_tail, expected_hidden) = if total <= head.saturating_add(tail) {
528                (all.clone(), Vec::new(), 0)
529            } else {
530                let head_count = head.min(total);
531                let tail_count = tail.min(total - head_count);
532                (all[..head_count].to_vec(), all[total - tail_count..].to_vec(), total - head_count - tail_count)
533            };
534            assert_eq!(preview.head, expected_head, "head for window ({head}, {tail})");
535            assert_eq!(preview.tail, expected_tail, "tail for window ({head}, {tail})");
536            assert_eq!(preview.hidden_count, expected_hidden, "hidden for window ({head}, {tail})");
537            assert_eq!(preview.total, total, "total for window ({head}, {tail})");
538        }
539    }
540
541    #[test]
542    fn excerpt_text_lines_matches_naive_slicing_for_all_tiny_inputs() {
543        // Exhaustive over the boundary-dense corner: every total up to 8
544        // lines against every window up to 3 + 3, fit and overflow both.
545        for total in 0..=8usize {
546            let text = (0..total).map(|i| format!("r{i}")).collect::<Vec<_>>().join("\n");
547            let all: Vec<&str> = text.lines().collect();
548            for head in 0..=3usize {
549                for tail in 0..=3usize {
550                    let preview = excerpt_text_lines(&text, head, tail);
551                    let (expected_head, expected_tail, expected_hidden) = if total <= head.saturating_add(tail) {
552                        (all.clone(), Vec::new(), 0)
553                    } else {
554                        let head_count = head.min(total);
555                        let tail_count = tail.min(total - head_count);
556                        (
557                            all[..head_count].to_vec(),
558                            all[total - tail_count..].to_vec(),
559                            total - head_count - tail_count,
560                        )
561                    };
562                    assert_eq!(preview.head, expected_head, "head for {total} lines, window ({head}, {tail})");
563                    assert_eq!(preview.tail, expected_tail, "tail for {total} lines, window ({head}, {tail})");
564                    assert_eq!(
565                        preview.hidden_count, expected_hidden,
566                        "hidden for {total} lines, window ({head}, {tail})"
567                    );
568                    assert_eq!(preview.total, total, "total for {total} lines, window ({head}, {tail})");
569                }
570            }
571        }
572    }
573
574    #[test]
575    fn excerpt_text_lines_with_limit_matches_legacy_split_for_all_tiny_inputs() {
576        // Exhaustive over limits 0..=6 and head preferences 0..=6: the oracle
577        // is the untouched `split_head_tail_preview_with_limit`, i.e. the
578        // exact pre-rewrite contract including the gap-row reservation.
579        for total in 0..=8usize {
580            let text = (0..total).map(|i| format!("r{i}")).collect::<Vec<_>>().join("\n");
581            let all: Vec<&str> = text.lines().collect();
582            for limit in 0..=6usize {
583                for preferred_head in 0..=6usize {
584                    let preview = excerpt_text_lines_with_limit(&text, limit, preferred_head);
585                    let legacy = split_head_tail_preview_with_limit(&all, limit, preferred_head);
586                    assert_eq!(
587                        preview.head,
588                        legacy.head.to_vec(),
589                        "head for {total} lines, limit {limit}, preferred {preferred_head}"
590                    );
591                    assert_eq!(
592                        preview.tail,
593                        legacy.tail.to_vec(),
594                        "tail for {total} lines, limit {limit}, preferred {preferred_head}"
595                    );
596                    assert_eq!(
597                        preview.hidden_count, legacy.hidden_count,
598                        "hidden for {total} lines, limit {limit}, preferred {preferred_head}"
599                    );
600                    assert_eq!(
601                        preview.total, legacy.total,
602                        "total for {total} lines, limit {limit}, preferred {preferred_head}"
603                    );
604                }
605            }
606        }
607    }
608
609    #[test]
610    fn tail_lines_keeps_last_window_and_short_inputs_whole() {
611        assert_eq!(tail_lines("l1\nl2\nl3\nl4\nl5", 2), vec!["l4", "l5"]);
612        // Exact fit and under-fit keep every line.
613        assert_eq!(tail_lines("l1\nl2", 2), vec!["l1", "l2"]);
614        assert_eq!(tail_lines("l1\nl2", 9), vec!["l1", "l2"]);
615        // Degenerate shapes keep nothing.
616        assert!(tail_lines("l1\nl2", 0).is_empty());
617        assert!(tail_lines("", 4).is_empty());
618    }
619
620    #[test]
621    fn tail_lines_matches_naive_slicing_for_all_tiny_inputs() {
622        for total in 0..=8usize {
623            let text = (0..total).map(|i| format!("r{i}")).collect::<Vec<_>>().join("\n");
624            let all: Vec<&str> = text.lines().collect();
625            for limit in 0..=5usize {
626                let expected = all[all.len().saturating_sub(limit)..].to_vec();
627                assert_eq!(tail_lines(&text, limit), expected, "tail of {total} lines with limit {limit}");
628            }
629        }
630    }
631
632    #[test]
633    fn excerpt_text_lines_streams_large_inputs() {
634        // 100k lines through a small window: the old materialize-then-slice
635        // path held every line transiently (~1.6 MB of refs); the ring keeps
636        // only the window while counting the same total.
637        let text = (0..100_000).map(|i| format!("row-{i}")).collect::<Vec<_>>().join("\n");
638        let preview = excerpt_text_lines(&text, 4, 6);
639        assert_eq!(preview.head, vec!["row-0", "row-1", "row-2", "row-3"]);
640        assert_eq!(
641            preview.tail,
642            vec![
643                "row-99994",
644                "row-99995",
645                "row-99996",
646                "row-99997",
647                "row-99998",
648                "row-99999"
649            ]
650        );
651        assert_eq!(preview.hidden_count, 100_000 - 10);
652        assert_eq!(preview.total, 100_000);
653    }
654
655    #[test]
656    fn excerpt_text_lines_with_limit_keeps_limit_sized_input_whole() {
657        // summary_window(6, 3) == (2, 3): head + tail == limit - 1 (gap row),
658        // so fit must be tested against `limit`, not the window sum. Six
659        // lines fit; the seventh overflows into the (2, 3) window.
660        let fit = excerpt_text_lines_with_limit("l1\nl2\nl3\nl4\nl5\nl6", 6, 3);
661        assert_eq!(fit.head, vec!["l1", "l2", "l3", "l4", "l5", "l6"]);
662        assert!(fit.tail.is_empty());
663        assert_eq!(fit.hidden_count, 0);
664        assert_eq!(fit.total, 6);
665
666        let overflow = excerpt_text_lines_with_limit("l1\nl2\nl3\nl4\nl5\nl6\nl7", 6, 3);
667        assert_eq!(overflow.head, vec!["l1", "l2"]);
668        assert_eq!(overflow.tail, vec!["l5", "l6", "l7"]);
669        assert_eq!(overflow.hidden_count, 2);
670        assert_eq!(overflow.total, 7);
671    }
672
673    #[test]
674    fn excerpt_text_lines_with_limit_handles_degenerate_limits() {
675        let zero = excerpt_text_lines_with_limit("l1\nl2", 0, 0);
676        assert!(zero.head.is_empty());
677        assert!(zero.tail.is_empty());
678        assert_eq!(zero.hidden_count, 2);
679        assert_eq!(zero.total, 2);
680
681        // limit <= 2 takes the all-tail window.
682        let tiny = excerpt_text_lines_with_limit("l1\nl2\nl3", 2, 9);
683        assert!(tiny.head.is_empty());
684        assert_eq!(tiny.tail, vec!["l2", "l3"]);
685        assert_eq!(tiny.hidden_count, 1);
686
687        let empty = excerpt_text_lines_with_limit("", 0, 0);
688        assert_eq!(empty.total, 0);
689        assert_eq!(empty.hidden_count, 0);
690    }
691
692    #[test]
693    fn condense_text_bytes_respects_utf8_boundaries() {
694        let mut content = "a".repeat(7);
695        content.push('é');
696        content.push_str("bbbbbbbb");
697
698        let preview = condense_text_bytes(&content, 8, 4);
699        assert!(preview.contains("bytes omitted"));
700        assert!(preview.is_char_boundary(0));
701    }
702
703    #[test]
704    fn tail_preview_text_keeps_last_lines_only() {
705        let input = (0..20).map(|index| format!("line-{index}")).collect::<Vec<_>>().join("\n");
706
707        let preview = tail_preview_text(&input, 40, 3);
708        assert!(preview.contains("bytes omitted"));
709        assert!(preview.contains("line-19"));
710        assert!(!preview.contains("line-1\n"));
711    }
712}