Repository navigation
perf: avoid per-token/line allocations in preprocessor and printer hot paths - #4154
keith-hall merged 3 commits into
Conversation
| #[inline] | ||
| pub(crate) fn has_ansi_introducer(s: &str) -> bool { | ||
| s.as_bytes().iter().any(|&b| b == 0x1B || b == 0xC2) | ||
| } | ||
|
|
There was a problem hiding this comment.
should this have been put above the comment for is_sequence_introducer, because now the comment is for the wrong method?
| /// True for ESC and the 8-bit C1 sequence introducers (DCS/SOS/CSI/OSC/PM/APC). | ||
| #[inline] | ||
| pub(crate) fn has_ansi_introducer(s: &str) -> bool { | ||
| s.as_bytes().iter().any(|&b| b == 0x1B || b == 0xC2) |
There was a problem hiding this comment.
I asked AI to review this PR and it had the following to say here:
has_ansi_introducer could get its own comment, e.g. “Fast pre-scan for bytes that can start an ANSI/VT escape sequence.”
While here, has_ansi_introducer is currently over-broad: it returns true for any 0xC2, but C1 introducers are only 0xC2 0x90/0x98/0x9B/0x9D/0x9E/0x9F. That means UTF-8 text containing U+0080..U+00BF takes the owned/parse path unnecessarily. A cheap tightening would be:
#[inline]
pub(crate) fn has_ansi_introducer(s: &str) -> bool {
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
0x1B => return true,
0xC2 => {
if matches!(
bytes.get(i + 1),
Some(0x90 | 0x98 | 0x9B | 0x9D | 0x9E | 0x9F)
) {
return true;
}
}
_ => {}
}
i += 1;
}
false
}Still a single byte scan, but avoids false positives for common Latin-1-range UTF-8. Could also be worth a small unit test covering "\u{00A9}" (no introducer) vs "\u{009B}31m" (CSI introducer).
| /// Strips ANSI escape sequences from the input. | ||
| pub fn strip_ansi(line: &str) -> String { | ||
| /// Strips ANSI escape sequences from the input, borrowing when none are present. | ||
| pub fn strip_ansi(line: &str) -> Cow<'_, str> { |
There was a problem hiding this comment.
as this is a public function, changing the return type deserves a changelog entry detailing the breakage and the migration path please. Same applies to the others as well. (One changelog entry would be fine, but I think important to somehow highlight it as a breaking change for users of bat as an API, and not have it drown amongst the numerous other entries in the changelog. Perhaps it deserves its own section, not sure. Maybe worth checking how breaking changes were communicated previously.)
…ernal preprocessor visibility
|
Thanks @keith-hall, pushed those fixes in 2f68e95:
|
|
Thanks, nice one, looks good. Unfortunately I merged another PR touching the word wrapping code and now there are conflicts. Would you be able to resolve them when you get chance please? |
…sor-utf8-and-tabs # Conflicts: # CHANGELOG.md # src/printer.rs # src/vscreen.rs
|
Thanks @keith-hall, merged |
Rendering lines in
InteractivePrinterandSimplePrinterallocates several intermediateStringbuffers per line and per syntax token even when the input is plain ASCII without tabs, ANSI escapes, or control bytes:expand_tabs,strip_ansi, andsanitize(src/preprocessor.rs) now returnCow<'_, str>, borrowing unchanged slices when no tabs, ANSI introducers (0x1B/0xC2), or sanitize triggers are present, and replacing" ".repeat(spaces)/"─".repeat(...)heap allocations with static slice chunks.replace_nonprintable(src/preprocessor.rs) replaces byte-by-byte 4-attempttry_parse_utf8_chardecoding and un-sizedString::new()withinput.utf8_chunks(), contiguous printable ASCII (0x21..=0x7E) bulk copies,output.extend(chr.escape_unicode()), and a hex lookup table for invalid bytes.InteractivePrinter::print_line(src/printer.rs) skipsformat!("{}{text}", self.ansi_style)andto_reset_sequence()whenAnsiStyle::is_empty()is true, hoistsline_bufout of the per-region loop in wrapped mode, and takes a fast path for printable ASCII regions that fit withinmax_widthwithout invokingunicode_segmentation::graphemesorgrapheme_width.Benchmarked over 15 interleaved release-build pairs with oa (
oa compare --git master --pairs 15 --check-output) on a 33,000-line Rust source file (~1.1 MiB):master(c3fe1436)bat --color=always --paging=never --wrap=character --terminal-width=100 --style=full --language=txtp = 0.0000)bat --show-all --paging=never --color=never --style=plainp = 0.0000)Output SHA-256 matched bit-for-bit on both commands (
a8ab4305f43e8866and1e1c3399360e23f2).cargo fmt --check,cargo clippy --lib -- -D warnings, andcargo test --lib(156 passed) all pass.