Skip to content

Commit 004100c

Browse files
committed
Process a single not-ASCII-printable char per iteration
This avoids having to collect a non-ASCII-printable run before processing it.
1 parent aaba972 commit 004100c

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

library/core/src/fmt/mod.rs

+5-8
Original file line numberDiff line numberDiff line change
@@ -2407,8 +2407,8 @@ impl Debug for str {
24072407
b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
24082408
}
24092409

2410-
// the outer loop here splits the string into chunks of printable ASCII, which is just skipped over,
2411-
// and chunks of other chars (unicode, or ASCII that needs escaping), which is handler per-`char`.
2410+
// the loop here first skips over runs of printable ASCII as a fast path.
2411+
// other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
24122412
let mut rest = self;
24132413
while rest.len() > 0 {
24142414
let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
@@ -2421,12 +2421,8 @@ impl Debug for str {
24212421
// SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
24222422
rest = unsafe { rest.get_unchecked(non_printable_start..) };
24232423

2424-
let printable_start =
2425-
rest.as_bytes().iter().position(|&b| !needs_escape(b)).unwrap_or(rest.len());
2426-
let prefix;
2427-
(prefix, rest) = rest.split_at(printable_start);
2428-
2429-
for c in prefix.chars() {
2424+
let mut chars = rest.chars();
2425+
if let Some(c) = chars.next() {
24302426
let esc = c.escape_debug_ext(EscapeDebugExtArgs {
24312427
escape_grapheme_extended: true,
24322428
escape_single_quote: false,
@@ -2439,6 +2435,7 @@ impl Debug for str {
24392435
}
24402436
printable_range.end += c.len_utf8();
24412437
}
2438+
rest = chars.as_str();
24422439
}
24432440

24442441
f.write_str(&self[printable_range])?;

0 commit comments

Comments
 (0)