Skip to content

Commit 1dba56e

Browse files
committed
optimize string escaping by writing chunks instead of individual chars
The previous implementation wrote each character individually using write! macro, which is inefficient for string formatting. The new implementation uses write_str to write larger chunks of the string at once, significantly reducing the number of write operations and formatting overhead. This change maintains the same escaping behavior but improves performance by avoiding character-by-character writes.
1 parent 052ad4a commit 1dba56e

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/ast/value.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -456,30 +456,34 @@ impl fmt::Display for EscapeQuotedString<'_> {
456456
// | `"A\"B\"A"` | default | `DoubleQuotedString(String::from("A\"B\"A"))` | `"A""B""A"` |
457457
let quote = self.quote;
458458
let mut previous_char = char::default();
459-
let mut peekable_chars = self.string.chars().peekable();
460-
while let Some(&ch) = peekable_chars.peek() {
459+
let mut start_idx = 0;
460+
let mut peekable_chars = self.string.char_indices().peekable();
461+
while let Some(&(idx, ch)) = peekable_chars.peek() {
461462
match ch {
462463
char if char == quote => {
463464
if previous_char == '\\' {
464-
write!(f, "{char}")?;
465465
peekable_chars.next();
466466
continue;
467467
}
468468
peekable_chars.next();
469-
if peekable_chars.peek().map(|c| *c == quote).unwrap_or(false) {
470-
write!(f, "{char}{char}")?;
471-
peekable_chars.next();
472-
} else {
473-
write!(f, "{char}{char}")?;
469+
match peekable_chars.peek() {
470+
Some((_, c)) if *c == quote => {
471+
peekable_chars.next();
472+
}
473+
_ => {
474+
// not calling .next(), so the quote at idx will be printed twice
475+
f.write_str(&self.string[start_idx..=idx])?;
476+
start_idx = idx;
477+
}
474478
}
475479
}
476480
_ => {
477-
write!(f, "{ch}")?;
478481
peekable_chars.next();
479482
}
480483
}
481484
previous_char = ch;
482485
}
486+
f.write_str(&self.string[start_idx..])?;
483487
Ok(())
484488
}
485489
}

0 commit comments

Comments
 (0)