about summary refs log tree commit diff
diff options
context:
space:
mode:
authorArpad Borsos <swatinem@swatinem.de>2024-05-20 12:04:21 +0200
committerArpad Borsos <swatinem@swatinem.de>2024-05-23 21:12:08 +0200
commit004100c222638c980b6509aba0ed4990181fa5dc (patch)
tree73067d57fa92951901b1875a98751434460ee10b
parentaaba972e06a35ca6988f41f31ca56d747eac4dc9 (diff)
Process a single not-ASCII-printable `char` per iteration
This avoids having to collect a non-ASCII-printable run before processing it.
-rw-r--r--library/core/src/fmt/mod.rs13
1 files changed, 5 insertions, 8 deletions
diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs
index b9f6b2d35c9..7f115d5cb20 100644
--- a/library/core/src/fmt/mod.rs
+++ b/library/core/src/fmt/mod.rs
@@ -2407,8 +2407,8 @@ impl Debug for str {
             b > 0x7E || b < 0x20 || b == b'\\' || b == b'"'
         }
 
-        // the outer loop here splits the string into chunks of printable ASCII, which is just skipped over,
-        // and chunks of other chars (unicode, or ASCII that needs escaping), which is handler per-`char`.
+        // the loop here first skips over runs of printable ASCII as a fast path.
+        // other chars (unicode, or ASCII that needs escaping) are then handled per-`char`.
         let mut rest = self;
         while rest.len() > 0 {
             let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
@@ -2421,12 +2421,8 @@ impl Debug for str {
             // SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
             rest = unsafe { rest.get_unchecked(non_printable_start..) };
 
-            let printable_start =
-                rest.as_bytes().iter().position(|&b| !needs_escape(b)).unwrap_or(rest.len());
-            let prefix;
-            (prefix, rest) = rest.split_at(printable_start);
-
-            for c in prefix.chars() {
+            let mut chars = rest.chars();
+            if let Some(c) = chars.next() {
                 let esc = c.escape_debug_ext(EscapeDebugExtArgs {
                     escape_grapheme_extended: true,
                     escape_single_quote: false,
@@ -2439,6 +2435,7 @@ impl Debug for str {
                 }
                 printable_range.end += c.len_utf8();
             }
+            rest = chars.as_str();
         }
 
         f.write_str(&self[printable_range])?;