Skip to content

Commit 5d255b2

Browse files
Boshenclaude
andcommitted
perf: optimize newline preservation using memchr
Replace byte-by-byte loops with efficient chunked filling: - Use memchr::memchr2 to find newline positions - Fill spaces in chunks between newlines using optimized fill() - Preserves correctness while restoring performance 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent f40d55a commit 5d255b2

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

src/lib.rs

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -229,28 +229,42 @@ fn consume_block_comments(buf: &mut [u8], i: &mut usize) -> State {
229229
match memchr::memchr(b'*', remaining) {
230230
Some(offset) => {
231231
*i += offset;
232-
// Preserve newlines in block comments
233-
for byte in &mut buf[cur..=*i] {
234-
if *byte != b'\n' && *byte != b'\r' {
235-
*byte = b' ';
236-
}
237-
}
232+
// Preserve newlines in block comments efficiently
233+
fill_non_newlines(&mut buf[cur..=*i]);
238234
MaybeCommentEnd
239235
}
240236
None => {
241237
let len = buf.len();
242238
*i = len - 1;
243-
// Preserve newlines in block comments
244-
for byte in &mut buf[cur..len] {
245-
if *byte != b'\n' && *byte != b'\r' {
246-
*byte = b' ';
247-
}
248-
}
239+
// Preserve newlines in block comments efficiently
240+
fill_non_newlines(&mut buf[cur..len]);
249241
InBlockComment
250242
}
251243
}
252244
}
253245

246+
/// Fill a buffer with spaces, preserving newlines for performance
247+
#[inline]
248+
fn fill_non_newlines(buf: &mut [u8]) {
249+
let mut pos = 0;
250+
while pos < buf.len() {
251+
// Find the next newline (\n or \r)
252+
match memchr::memchr2(b'\n', b'\r', &buf[pos..]) {
253+
Some(offset) => {
254+
// Fill everything before the newline with spaces
255+
buf[pos..pos + offset].fill(b' ');
256+
// Skip the newline character
257+
pos += offset + 1;
258+
}
259+
None => {
260+
// No more newlines, fill the rest
261+
buf[pos..].fill(b' ');
262+
break;
263+
}
264+
}
265+
}
266+
}
267+
254268
#[inline(always)]
255269
fn top(c: &mut u8) -> State {
256270
match *c {

0 commit comments

Comments
 (0)