Skip to content

Optimize text_util - #61

Merged
letmutex merged 3 commits into
mainfrom
optimize-text-util
Nov 15, 2025
Merged

letmutex merged 3 commits into
mainfrom
optimize-text-util

Conversation

@letmutex

@letmutex letmutex commented Nov 15, 2025 •

Copy link
Copy Markdown
Owner

Continue the unfinished task in #60, thanks to AI

Summary by CodeRabbit

  • Refactor

    • Optimized text-processing routines to reduce allocations and improve string handling, preserving existing behavior.
  • Benchmarks

    • Added a new string-concatenation benchmark and narrowed which benchmark target is executed.
    • Updated benchmark results and README: modest timing improvement, fewer outliers, and revised summary timestamp.

@coderabbitai

coderabbitai Bot commented Nov 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Benchmark README and runner updated; a new Criterion string-concat benchmark added; Cargo manifest registers the new bench; core text utilities in src/text_util.rs were refactored to allocation-aware implementations while preserving public APIs and behavior.

Changes

Cohort / File(s) Summary
Benchmark README
benches/README.md
Updated benchmark measurements and summary: convert() time changed (~24.8 ms → ~19.97 ms), outliers reduced (4 → 1), assessment message changed to “Change within noise threshold.” Footer timestamp updated.
Benchmark runner script
benches/bench.ts
Narrows cargo invocation to a specific target by switching from cargo bench to cargo bench --bench convert_bench; output capture/parsing and README writing retained.
New Criterion benchmark
benches/str_concat_bench.rs
Adds str_concat_bench.rs with a concat_strings! macro and Criterion benchmarks comparing format!() vs. a pre-sized concatenation; registers bench group and main.
Cargo manifest
Cargo.toml
Adds a new [[bench]] entry: name = "str_concat_bench", harness = false.
Text Utility Optimizations
src/text_util.rs
Refactors functions to reduce allocations and use std utilities: strip_leading_whitespace/strip_trailing_whitespace use trim_start/trim_end with index math; join_contents pre-allocates and trims trailing newlines; compress_whitespace lazily allocates using char_indices and returns Borrowed/Owned appropriately; indent_text_except_first_line precomputes capacity and appends lines. Public signatures unchanged.

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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Inspect src/text_util.rs for off-by-one and edge cases (empty input, all-whitespace, trailing newlines).
  • Verify benches/bench.ts parsing still finds the "convert()" section when only that bench runs.
  • Confirm Criterion benchmark correctness and measurement configuration in benches/str_concat_bench.rs.

Poem

🐰 I nibbled bytes and stitched a seam,

Old spaces trimmed, new benches beam.
Strings hop light with kinder care,
Fewer hops, more speed to spare.
🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Optimize text_util' directly and clearly describes the main change: performance optimizations to the text_util module through refactored implementations in src/text_util.rs.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch optimize-text-util

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ddb80d0 and 9bdaca8.

📒 Files selected for processing (1)
  • Cargo.toml (1 hunks)
🔇 Additional comments (1)
Cargo.toml (1)

29-31: Benchmark declaration verified and correct.

The str_concat_bench target in Cargo.toml is properly configured with harness = false to align with Criterion's setup. The corresponding implementation file (benches/str_concat_bench.rs) exists and demonstrates a valid Criterion benchmark structure with appropriate imports and macro definitions for string concatenation testing.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 &usize to len, 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, len correctly accumulates the total byte length and the macro becomes usable by callers like indent_text_except_first_line.

🧹 Nitpick comments (3)
src/text_util.rs (3)

99-101: join_contents preallocation and separator logic mostly good; minor capacity nit

The 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 \n separator 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 behavior

The 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 line

The capacity estimate (text.len() + (line_count - 1) * indent) is reasonable and should reduce reallocations. However, using concat_strings!(indent_text, line) still allocates a fresh String for every indented line before pushing it into result.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 41b7d82 and 53a3d2f.

📒 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 consistent

The 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 safe

Using trim_start/trim_end plus 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 cases

The 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
benches/str_concat_bench.rs (2)

1-1: Remove unused extern crate declaration.

The htmd crate 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 using String::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

📥 Commits

Reviewing files that changed from the base of the PR and between 53a3d2f and ddb80d0.

📒 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 added str_concat_bench won't be run by this script. Confirm this is intentional—perhaps str_concat_bench is 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.

Comment thread benches/str_concat_bench.rs Resolved
@letmutex
letmutex merged commit f78f065 into main Nov 15, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Nov 20, 2025
@letmutex letmutex mentioned this pull request Nov 20, 2025
2 tasks done
@letmutex
letmutex deleted the optimize-text-util branch July 27, 2026 03:35
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.

1 participant