1
0
mirror of https://github.com/sharkdp/bat synced 2026-07-28 17:51:44 +00:00

Fix capacity-overflow panic in print_snip at --terminal-width 1

`InteractivePrinter::print_snip` computes the snip separator width as
`term_width - panel_count - snip_left_count - title_count`. At `--terminal-width 1`
the panel is disabled and `title_count == 2`, so the subtraction underflows
`usize` (release has no overflow-checks, so it wraps to ~usize::MAX); `str::repeat`
then aborts with "capacity overflow" whenever a snip separator is emitted (two or
more disjoint line ranges, or a diff gap) — which the default style does.

Use `saturating_sub` for the repeat counts so they clamp to 0 instead of
underflowing. Added an integration test.
This commit is contained in:
weili
2026-06-16 06:58:55 +00:00
parent af1f53d9a9
commit d28aa4a8b4
3 changed files with 29 additions and 3 deletions
+15 -3
View File
@@ -603,11 +603,23 @@ impl Printer for InteractivePrinter<'_> {
let title = "8<";
let title_count = title.chars().count();
let snip_left = "".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
let snip_left = "".repeat(
self.config
.term_width
.saturating_sub(panel_count)
.saturating_sub(title_count / 2)
/ 4,
);
let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
let snip_right =
"".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
let snip_right = "".repeat(
self.config
.term_width
.saturating_sub(panel_count)
.saturating_sub(snip_left_count)
.saturating_sub(title_count)
/ 2,
);
writeln!(
handle,