perf(tui): reduce allocations and add compiler hints in md-table pipeline

Replace clone with mem::take in finalize(), return Cow from
unwrap_markdown_fences for zero-copy on fence-free messages, use
index-based iteration in reflow loop, add #[inline] on ~20 hot-path
functions, add with_capacity hints on hot Vecs/Strings, box large
ActiveFence variant, and eliminate minor allocations (into_iter,
Span::from for literals, write!-based plain_text, redundant .max(1)).
This commit is contained in:
Felipe Coury
2026-04-06 13:42:16 -03:00
committed by Felipe Coury
parent c0db2f0dc1
commit 36761c5863
5 changed files with 107 additions and 69 deletions
+3 -1
View File
@@ -3421,7 +3421,9 @@ impl App {
}
let width = tui.terminal.size()?.width;
for cell in self.transcript_cells.clone() {
// Iterate by index to avoid cloning the Vec and bumping Arc refcounts.
for i in 0..self.transcript_cells.len() {
let cell = self.transcript_cells[i].clone();
self.insert_history_cell_lines(tui, cell.as_ref(), width);
}
+35 -39
View File
@@ -20,6 +20,7 @@
//! info string is `md` or `markdown` AND whose body contains a
//! header+delimiter pair, and degrades gracefully on unclosed fences.
use ratatui::text::Line;
use std::borrow::Cow;
use std::ops::Range;
use std::path::Path;
@@ -82,9 +83,10 @@ pub(crate) fn append_markdown_agent_with_cwd(
/// The fence unwrapping is intentionally conservative: it buffers the entire fence body before
/// deciding, and an unclosed fence at end-of-input is re-emitted with its opening line so partial
/// streams degrade to code display.
fn unwrap_markdown_fences(markdown_source: &str) -> String {
fn unwrap_markdown_fences<'a>(markdown_source: &'a str) -> Cow<'a, str> {
// Zero-copy fast path: most messages contain no fences at all.
if !markdown_source.contains("```") && !markdown_source.contains("~~~") {
return markdown_source.to_string();
return Cow::Borrowed(markdown_source);
}
#[derive(Clone, Copy)]
@@ -176,20 +178,24 @@ fn unwrap_markdown_fences(markdown_source: &str) -> String {
}
fn content_from_ranges(source: &str, ranges: &[Range<usize>]) -> String {
let mut content = String::new();
let total_len: usize = ranges.iter().map(ExactSizeIterator::len).sum();
let mut content = String::with_capacity(total_len);
for range in ranges {
content.push_str(&source[range.clone()]);
content.push_str(&source[range.start..range.end]);
}
content
}
struct MarkdownCandidateData {
fence: Fence,
opening_range: Range<usize>,
content_ranges: Vec<Range<usize>>,
}
// Box the large variant to keep ActiveFence small (~pointer-sized).
enum ActiveFence {
Passthrough(Fence),
MarkdownCandidate {
fence: Fence,
opening_range: Range<usize>,
content_ranges: Vec<Range<usize>>,
},
MarkdownCandidate(Box<MarkdownCandidateData>),
}
let mut out = String::with_capacity(markdown_source.len());
@@ -215,34 +221,26 @@ fn unwrap_markdown_fences(markdown_source: &str) -> String {
active_fence = Some(ActiveFence::Passthrough(fence));
}
}
ActiveFence::MarkdownCandidate {
fence,
opening_range,
mut content_ranges,
} => {
if is_close_fence(line, fence) {
ActiveFence::MarkdownCandidate(mut data) => {
if is_close_fence(line, data.fence) {
if markdown_fence_contains_table(&content_from_ranges(
markdown_source,
&content_ranges,
), fence.is_blockquoted)
&data.content_ranges,
), data.fence.is_blockquoted)
{
for range in content_ranges {
for range in data.content_ranges {
push_source_range(range);
}
} else {
push_source_range(opening_range);
for range in content_ranges {
push_source_range(data.opening_range);
for range in data.content_ranges {
push_source_range(range);
}
push_source_range(line_range);
}
} else {
content_ranges.push(line_range);
active_fence = Some(ActiveFence::MarkdownCandidate {
fence,
opening_range,
content_ranges,
});
data.content_ranges.push(line_range);
active_fence = Some(ActiveFence::MarkdownCandidate(data));
}
}
}
@@ -251,11 +249,13 @@ fn unwrap_markdown_fences(markdown_source: &str) -> String {
if let Some((fence, is_markdown)) = parse_open_fence(line) {
if is_markdown {
active_fence = Some(ActiveFence::MarkdownCandidate {
fence,
opening_range: line_range,
content_ranges: Vec::new(),
});
active_fence = Some(ActiveFence::MarkdownCandidate(Box::new(
MarkdownCandidateData {
fence,
opening_range: line_range,
content_ranges: Vec::new(),
},
)));
} else {
push_source_range(line_range);
active_fence = Some(ActiveFence::Passthrough(fence));
@@ -269,20 +269,16 @@ fn unwrap_markdown_fences(markdown_source: &str) -> String {
if let Some(active) = active_fence {
match active {
ActiveFence::Passthrough(_) => {}
ActiveFence::MarkdownCandidate {
opening_range,
content_ranges,
..
} => {
push_source_range(opening_range);
for range in content_ranges {
ActiveFence::MarkdownCandidate(data) => {
push_source_range(data.opening_range);
for range in data.content_ranges {
push_source_range(range);
}
}
}
}
out
Cow::Owned(out)
}
#[cfg(test)]
+31 -19
View File
@@ -130,13 +130,16 @@ struct TableCell {
lines: Vec<Line<'static>>,
}
// TableCell mutators inlined — called per-span during table event parsing.
impl TableCell {
#[inline]
fn ensure_line(&mut self) {
if self.lines.is_empty() {
self.lines.push(Line::default());
}
}
#[inline]
fn push_span(&mut self, span: Span<'static>) {
self.ensure_line();
if let Some(line) = self.lines.last_mut() {
@@ -144,21 +147,23 @@ impl TableCell {
}
}
#[inline]
fn hard_break(&mut self) {
self.lines.push(Line::default());
}
fn plain_text(&self) -> String {
self.lines
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span.content.clone())
.collect::<String>()
})
.collect::<Vec<_>>()
.join(" ")
use std::fmt::Write;
let mut buf = String::new();
for (i, line) in self.lines.iter().enumerate() {
if i > 0 {
buf.push(' ');
}
for span in &line.spans {
let _ = write!(buf, "{}", span.content);
}
}
buf
}
}
@@ -956,8 +961,8 @@ where
};
}
let mut spillover_rows: Vec<TableCell> = Vec::new();
let mut rows: Vec<Vec<TableCell>> = Vec::new();
let mut spillover_rows: Vec<TableCell> = Vec::with_capacity(4);
let mut rows: Vec<Vec<TableCell>> = Vec::with_capacity(table_state.rows.len());
for (row_idx, row) in table_state.rows.iter().enumerate() {
let next_row = table_state.rows.get(row_idx + 1);
// pulldown-cmark accepts body rows without pipes, which can turn a following paragraph
@@ -1002,7 +1007,7 @@ where
};
let border_style = Style::new().dim();
let mut out = Vec::new();
let mut out = Vec::with_capacity(3 + rows.len() * 2);
out.push(self.render_border_line('┌', '┬', '┐', &column_widths, border_style));
out.extend(self.render_table_row(
&header,
@@ -1241,13 +1246,13 @@ where
style: Style,
) -> Line<'static> {
let mut spans = Vec::with_capacity(column_widths.len() * 2 + 1);
spans.push(Span::styled(left.to_string(), style));
spans.push(Span::styled(String::from(left), style));
for (idx, width) in column_widths.iter().enumerate() {
spans.push(Span::styled("─".repeat(*width + 2), style));
if idx + 1 == column_widths.len() {
spans.push(Span::styled(right.to_string(), style));
spans.push(Span::styled(String::from(right), style));
} else {
spans.push(Span::styled(sep.to_string(), style));
spans.push(Span::styled(String::from(sep), style));
}
}
Line::from(spans)
@@ -1265,12 +1270,12 @@ where
.zip(column_widths)
.map(|(cell, width)| self.wrap_cell(cell, *width))
.collect();
let row_height = wrapped_cells.iter().map(Vec::len).max().unwrap_or(1).max(1);
let row_height = wrapped_cells.iter().map(Vec::len).max().unwrap_or(1);
let mut out = Vec::with_capacity(row_height);
for row_line in 0..row_height {
let mut spans = Vec::new();
spans.push(Span::styled("│".to_string(), border_style));
spans.push(Span::styled("│", border_style));
for (column, width) in column_widths.iter().enumerate() {
spans.push(Span::raw(" "));
let line = wrapped_cells[column]
@@ -1292,7 +1297,7 @@ where
spans.push(Span::raw(" ".repeat(right_padding)));
}
spans.push(Span::raw(" "));
spans.push(Span::styled("│".to_string(), border_style));
spans.push(Span::styled("│", border_style));
}
out.push(Line::from(spans));
}
@@ -1464,14 +1469,20 @@ where
.any(|word| word.eq_ignore_ascii_case("html"))
}
// Width-measurement helpers inlined — called per-cell during table column
// width computation, which runs on every re-render.
#[inline]
fn spans_display_width(spans: &[Span<'_>]) -> usize {
spans.iter().map(|span| span.content.width()).sum()
}
#[inline]
fn line_display_width(line: &Line<'_>) -> usize {
Self::spans_display_width(&line.spans)
}
#[inline]
fn cell_display_width(cell: &TableCell) -> usize {
cell.lines
.iter()
@@ -1480,6 +1491,7 @@ where
.unwrap_or(0)
}
#[inline]
fn longest_token_width(text: &str) -> usize {
text.split_whitespace().map(str::width).max().unwrap_or(0)
}
+24 -7
View File
@@ -99,8 +99,8 @@ impl StreamCore {
Self {
state: StreamState::new(width, cwd),
width,
raw_source: String::new(),
rendered_lines: Vec::new(),
raw_source: String::with_capacity(1024),
rendered_lines: Vec::with_capacity(64),
enqueued_stable_len: 0,
emitted_stable_len: 0,
cwd: cwd.to_path_buf(),
@@ -171,14 +171,20 @@ impl StreamCore {
step
}
// Trivial StreamCore accessors inlined — called on every animation tick
// and render frame during active streaming.
#[inline]
fn is_idle(&self) -> bool {
self.state.is_idle()
}
#[inline]
fn queued_lines(&self) -> usize {
self.state.queued_len()
}
#[inline]
fn oldest_queued_age(&self, now: Instant) -> Option<Duration> {
self.state.oldest_queued_age(now)
}
@@ -187,11 +193,13 @@ impl StreamCore {
///
/// The tail starts at `enqueued_stable_len` -- everything from that offset to
/// the end of `rendered_lines` is displayed live in the active-cell slot.
#[inline]
fn current_tail_lines(&self) -> Vec<Line<'static>> {
let start = self.enqueued_stable_len.min(self.rendered_lines.len());
self.rendered_lines[start..].to_vec()
}
#[inline]
fn has_tail(&self) -> bool {
self.enqueued_stable_len < self.rendered_lines.len()
}
@@ -413,8 +421,8 @@ impl StreamController {
return (None, None);
}
// Capture the source before reset clears it.
let source = self.core.raw_source.clone();
// Move ownership — source is consumed before reset() clears it.
let source = std::mem::take(&mut self.core.raw_source);
let out = self.emit(remaining);
self.core.reset();
(out, Some(source))
@@ -433,6 +441,10 @@ impl StreamController {
(self.emit(step), self.core.is_idle())
}
// Thin StreamController accessors inlined — one-liner delegates called
// on every render frame and animation tick.
#[inline]
pub(crate) fn queued_lines(&self) -> usize {
self.core.queued_lines()
}
@@ -441,14 +453,17 @@ impl StreamController {
self.core.oldest_queued_age(now)
}
#[inline]
pub(crate) fn current_tail_lines(&self) -> Vec<Line<'static>> {
self.core.current_tail_lines()
}
#[inline]
pub(crate) fn tail_starts_stream(&self) -> bool {
!self.header_emitted && self.core.enqueued_stable_len == 0
}
#[inline]
pub(crate) fn has_live_tail(&self) -> bool {
self.core.has_tail()
}
@@ -509,7 +524,8 @@ impl PlanStreamController {
return (None, None);
}
let source = self.core.raw_source.clone();
// Move ownership — source is consumed before reset() clears it.
let source = std::mem::take(&mut self.core.raw_source);
let out = self.emit(remaining, true);
self.core.reset();
(out, Some(source))
@@ -528,6 +544,7 @@ impl PlanStreamController {
(self.emit(step, false), self.core.is_idle())
}
#[inline]
pub(crate) fn queued_lines(&self) -> usize {
self.core.queued_lines()
}
@@ -549,7 +566,7 @@ impl PlanStreamController {
return None;
}
let mut out_lines: Vec<Line<'static>> = Vec::new();
let mut out_lines: Vec<Line<'static>> = Vec::with_capacity(4);
let is_stream_continuation = self.header_emitted;
if !self.header_emitted {
out_lines.push(vec!["• ".dim(), "Proposed Plan".bold()].into());
@@ -557,7 +574,7 @@ impl PlanStreamController {
self.header_emitted = true;
}
let mut plan_lines: Vec<Line<'static>> = Vec::new();
let mut plan_lines: Vec<Line<'static>> = Vec::with_capacity(4);
if !self.top_padding_emitted {
plan_lines.push(Line::from(" "));
self.top_padding_emitted = true;
+14 -3
View File
@@ -40,8 +40,8 @@ pub(crate) fn parse_table_segments(line: &str) -> Option<Vec<&str>> {
let content = content.strip_suffix('|').unwrap_or(content);
let segments: Vec<&str> = split_unescaped_pipe(content)
.iter()
.map(|s| s.trim())
.into_iter()
.map(str::trim)
.collect();
(!segments.is_empty()).then_some(segments)
}
@@ -52,7 +52,7 @@ pub(crate) fn parse_table_segments(line: &str) -> Option<Vec<&str>> {
/// The backslash remains in the segment (this is structure detection, not
/// rendering).
fn split_unescaped_pipe(content: &str) -> Vec<&str> {
let mut segments = Vec::new();
let mut segments = Vec::with_capacity(8);
let mut start = 0;
let bytes = content.as_bytes();
let mut i = 0;
@@ -72,14 +72,19 @@ fn split_unescaped_pipe(content: &str) -> Vec<&str> {
segments
}
// Small table-detection helpers inlined for the streaming hot path — they are
// called on every source line during incremental holdback scanning.
/// Whether `line` looks like a table header row (has pipe-separated
/// segments with at least one non-empty cell).
#[inline]
pub(crate) fn is_table_header_line(line: &str) -> bool {
parse_table_segments(line).is_some_and(|segments| segments.iter().any(|s| !s.is_empty()))
}
/// Whether a single segment matches the `---`, `:---`, `---:`, or `:---:`
/// alignment-colon syntax used in markdown table delimiter rows.
#[inline]
fn is_table_delimiter_segment(segment: &str) -> bool {
let trimmed = segment.trim();
if trimmed.is_empty() {
@@ -92,6 +97,7 @@ fn is_table_delimiter_segment(segment: &str) -> bool {
/// Whether `line` is a valid table delimiter row (every segment passes
/// [`is_table_delimiter_segment`]).
#[inline]
pub(crate) fn is_table_delimiter_line(line: &str) -> bool {
parse_table_segments(line)
.is_some_and(|segments| segments.into_iter().all(is_table_delimiter_segment))
@@ -128,6 +134,7 @@ pub(crate) struct FenceTracker {
}
impl FenceTracker {
#[inline]
pub(crate) fn new() -> Self {
Self { state: None }
}
@@ -170,6 +177,7 @@ impl FenceTracker {
}
/// Current fence context for the most-recently-advanced line.
#[inline]
pub(crate) fn kind(&self) -> FenceKind {
self.state.map_or(FenceKind::Outside, |(_, _, k)| k)
}
@@ -180,6 +188,7 @@ impl FenceTracker {
/// Recognises backtick and tilde fences with a minimum run of 3.
/// The input should already have leading whitespace and blockquote prefixes
/// stripped.
#[inline]
pub(crate) fn parse_fence_marker(line: &str) -> Option<(char, usize)> {
let first = line.as_bytes().first().copied()?;
if first != b'`' && first != b'~' {
@@ -195,6 +204,7 @@ pub(crate) fn parse_fence_marker(line: &str) -> Option<(char, usize)> {
/// Whether the info string after a fence marker indicates markdown content.
///
/// Matches `md` and `markdown` (case-insensitive).
#[inline]
pub(crate) fn is_markdown_fence_info(trimmed_line: &str, marker_len: usize) -> bool {
let info = trimmed_line[marker_len..]
.split_whitespace()
@@ -207,6 +217,7 @@ pub(crate) fn is_markdown_fence_info(trimmed_line: &str, marker_len: usize) -> b
///
/// Tables can appear inside blockquotes (`> | A | B |`), so the holdback
/// scanner must strip these markers before checking for table syntax.
#[inline]
pub(crate) fn strip_blockquote_prefix(line: &str) -> &str {
let mut rest = line.trim_start();
loop {