Repository navigation
Optimize text_util - #61
Conversation
WalkthroughBenchmark README and runner updated; a new Criterion string-concat benchmark added; Cargo manifest registers the new bench; core text utilities in Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Runner as benches/bench.ts
participant Cargo as cargo
participant BenchOut as stdout
participant Parser as benches/bench.ts (parser)
participant FS as filesystem
Runner->>Cargo: cargo bench --bench convert_bench
Note over Cargo: runs only the named bench target
Cargo->>BenchOut: emits benchmark output (includes "convert()")
Parser->>BenchOut: scan for "convert()" start index
Parser->>Parser: extract results, compute summary
Parser->>FS: write benches/README.md (updated metrics & timestamp)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🔇 Additional comments (1)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/text_util.rs (1)
255-265: concat_strings! macro has a type error and won’t compile as written
len += &$x.len();attempts to add a&usizetolen, which is a plain integer; this doesn’t type‑check and will prevent the crate from compiling.You likely meant to add the length value itself:
macro_rules! concat_strings { ($($x:expr),*) => {{ let mut len = 0; $( - len += &$x.len(); + len += $x.len(); )* let mut result = String::with_capacity(len); $( result.push_str(&$x); )* result }}; }With this change,
lencorrectly accumulates the total byte length and the macro becomes usable by callers likeindent_text_except_first_line.
🧹 Nitpick comments (3)
src/text_util.rs (3)
99-101: join_contents preallocation and separator logic mostly good; minor capacity nitThe new implementation avoids per-iteration string reconstruction and keeps the “at most two newlines between clips” behavior by trimming boundary newlines and inserting a 0–2
\nseparator before appending the next chunk. One nit:capacity = contents.iter().map(String::len).sum()doesn’t account for up to 2 separator newlines per join, so in worst cases you may still get a reallocation.If you want to push the optimization further, consider slightly overestimating:
- let capacity = contents.iter().map(String::len).sum(); + let content_bytes: usize = contents.iter().map(String::len).sum(); + // Over-approximate up to 2 newlines between items. + let capacity = content_bytes + contents.len().saturating_sub(1) * 2;Not required, but it would better align with the preallocation goal.
Also applies to: 117-129
133-186: compress_whitespace lazy allocation is solid; clarify ASCII vs Unicode behaviorThe lazy-allocation approach (only allocating on the first actual change and copying the untouched prefix) looks correct and efficient:
- Single spaces are preserved as-is.
- Runs of ASCII whitespace collapse to a single space.
- Non‑space ASCII whitespace (
\n,\t, etc.) are normalized to a space.- When no changes occur, you correctly return
Cow::Borrowed.One semantic detail: the predicate is
c.is_ascii_whitespace(), so non‑ASCII whitespace (e.g., certain Unicode spaces) will not be collapsed. If you intend to normalize all Unicode whitespace, consider:- if c.is_ascii_whitespace() { + if c.is_whitespace() {Otherwise, it may be worth documenting that this function intentionally only compresses ASCII whitespace.
188-212: indent_text_except_first_line capacity precomputation is good; avoid extra concat per lineThe capacity estimate (
text.len() + (line_count - 1) * indent) is reasonable and should reduce reallocations. However, usingconcat_strings!(indent_text, line)still allocates a freshStringfor every indented line before pushing it intoresult.For this hot path, you can remove that extra allocation and rely on the already-computed
indent_text:- if idx == 0 || line.is_empty() { - result.push_str(line); - } else { - result.push_str(&concat_strings!(indent_text, line)); - } + if idx == 0 || line.is_empty() { + result.push_str(line); + } else { + result.push_str(&indent_text); + result.push_str(line); + }That would fully capitalize on the preallocation and keep indentation logic straightforward.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
benches/README.md(1 hunks)src/text_util.rs(4 hunks)
🔇 Additional comments (3)
benches/README.md (1)
18-23: Benchmark result updates look consistentThe new timing, change percentages, outlier breakdown, and timestamp are internally consistent and accurately reflect an updated benchmark run. No issues from a docs/metrics perspective.
Also applies to: 26-26
src/text_util.rs (2)
48-57: Whitespace strip refactor is correct and UTF‑8 safeUsing
trim_start/trim_endplus length differences to derive slice boundaries is sound for UTF‑8, and the returned(stripped, Option<whitespace>)pairs preserve the original prefix/suffix without extra allocation when nothing is trimmed. This is a clean, more idiomatic replacement for manual loops.Also applies to: 60-69
272-289: Tests for index_of_markdown_ordered_item_dot cover key casesThe new tests exercise valid ordered-list markers (
"1. ","12. ","12345. ", with and without trailing newline) and a good range of invalid patterns (decimals, leading space, missing space, non-numeric prefix/suffix). This gives solid coverage for the parsing logic.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
benches/str_concat_bench.rs (2)
1-1: Remove unused extern crate declaration.The
htmdcrate is declared but never used in this benchmark file.Apply this diff:
-extern crate htmd; - use std::{str::FromStr, time::Duration};
21-33: Simplify string initialization.Lines 22-23 use
String::from_str().unwrap()for string literals, which is unnecessarily verbose. Consider usingString::from()or.to_string()instead.Apply this diff for more idiomatic code:
fn benchmark(c: &mut Criterion) { - let a = String::from_str("Hello World").unwrap(); - let b = String::from_str("Lorem ipsum").unwrap(); + let a = String::from("Hello World"); + let b = String::from("Lorem ipsum"); let z = "Less is more";
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
Cargo.toml(1 hunks)benches/README.md(1 hunks)benches/bench.ts(1 hunks)benches/str_concat_bench.rs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- benches/README.md
🔇 Additional comments (3)
Cargo.toml (1)
29-33: LGTM!The new benchmark target is properly configured following Rust conventions for Criterion benchmarks.
benches/bench.ts (1)
13-13: Verify the intentional exclusion of the new benchmark.The change narrows the benchmark execution to only
convert_bench, which means the newly addedstr_concat_benchwon't be run by this script. Confirm this is intentional—perhapsstr_concat_benchis meant for internal development/comparison rather than regular benchmark reporting.benches/str_concat_bench.rs (1)
35-40: LGTM!The Criterion configuration is properly set up with a reasonable 20-second measurement time for stable benchmark results.
Continue the unfinished task in #60, thanks to AI
Summary by CodeRabbit
Refactor
Benchmarks