Skip to content

fix: panic on an empty content match at end of line - #1201

Merged
Canop merged 1 commit into
Canop:mainfrom
VXNCXNX:fix/content-match-empty-at-eol
Aug 16, 2026
Merged

Canop merged 1 commit into
Canop:mainfrom
VXNCXNX:fix/content-match-empty-at-eol

Conversation

@VXNCXNX

@VXNCXNX VXNCXNX commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Searching cr/$/ in a directory containing a file with CRLF line endings kills broot.

/tmp/brepro2 with crlf.txt (hello\r\nworld\r\n) and tabend.txt (abc\t\n), driven through the real TUI under tmux, typing cr/$/:

before:  EXIT=101
         panicked at src/content_search/content_match.rs:38:16:
         index out of bounds: the len is 4 but the index is 4

after:   no panic, session still alive, filter applied normally

Cause

The left-trimming loop tests the two conditions in the wrong order:

while (hay[extract_start] == 32) && extract_start < pos {

hay[extract_start] is evaluated before the bound is checked. An empty match at the very end of a line gives pos == hay.len(), so the index read is out of range. $ on a line ending in a control character (the \r of CRLF, or a trailing tab) is a natural way to produce that.

The fix

Swap the two operands so the bound is checked first. That is the whole change; && short-circuits, so nothing else needs to move.

Verification

Three tests in content_match.rs: the empty-match-at-end regression, plus two that pin the existing trimming behaviour (leading spaces are still dropped, and trimming still stops at the needle) so the reorder cannot quietly change what the function does.

Reverting only the condition order fails the regression test with the original panic:

test empty_match_at_end_of_line_doesnt_panic ... FAILED
panicked at src/content_search/content_match.rs:38:16:
index out of bounds: the len is 4 but the index is 4

cargo test is 59 + 7 passed, cargo clippy --all-targets is clean. cargo fmt --check reports pre-existing diffs elsewhere in the repo (rustfmt.toml uses nightly-only options), but none in the file I touched.

Disclosure: written with AI assistance (Claude Code). I reproduced the panic in a real terminal against a binary built from master, confirmed it is gone on the fixed binary, and ran the mutation check myself.

The left-trimming loop indexed hay before checking the bound, so an empty
match at pos == hay.len() read out of bounds. Searching cr/$/ in a file
with CRLF endings killed broot with exit 101.
@Canop
Canop merged commit dfd25e0 into Canop:main Aug 16, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants