Skip to content

Commit 0334c45

Browse files
committed
Write char::DebugEscape sequences using write_str
Instead of writing each `char` of an escape sequence one by one, this delegates to `Display`, which uses `write_str` internally in order to write the whole escape sequence at once.
1 parent f092f73 commit 0334c45

File tree

2 files changed

+6
-9
lines changed

2 files changed

+6
-9
lines changed

Diff for: library/core/benches/str/debug.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ fn ascii_escapes(b: &mut Bencher) {
4444
assert_fmt(
4545
s,
4646
r#""some\tmore\tascii\ttext\nthis time with some \"escapes\", also 64 byte""#,
47-
21,
47+
15,
4848
);
4949
b.iter(|| {
5050
black_box(format!("{:?}", black_box(s)));
@@ -72,7 +72,7 @@ fn mostly_unicode(b: &mut Bencher) {
7272
#[bench]
7373
fn mixed(b: &mut Bencher) {
7474
let s = "\"❤️\"\n\"hűha ez betű\"\n\"кириллических букв\".";
75-
assert_fmt(s, r#""\"❤\u{fe0f}\"\n\"hűha ez betű\"\n\"кириллических букв\".""#, 36);
75+
assert_fmt(s, r#""\"❤\u{fe0f}\"\n\"hűha ez betű\"\n\"кириллических букв\".""#, 21);
7676
b.iter(|| {
7777
black_box(format!("{:?}", black_box(s)));
7878
});

Diff for: library/core/src/fmt/mod.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -2409,9 +2409,7 @@ impl Debug for str {
24092409
// If char needs escaping, flush backlog so far and write, else skip
24102410
if esc.len() != 1 {
24112411
f.write_str(&self[from..i])?;
2412-
for c in esc {
2413-
f.write_char(c)?;
2414-
}
2412+
Display::fmt(&esc, f)?;
24152413
from = i + c.len_utf8();
24162414
}
24172415
}
@@ -2431,13 +2429,12 @@ impl Display for str {
24312429
impl Debug for char {
24322430
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
24332431
f.write_char('\'')?;
2434-
for c in self.escape_debug_ext(EscapeDebugExtArgs {
2432+
let esc = self.escape_debug_ext(EscapeDebugExtArgs {
24352433
escape_grapheme_extended: true,
24362434
escape_single_quote: true,
24372435
escape_double_quote: false,
2438-
}) {
2439-
f.write_char(c)?
2440-
}
2436+
});
2437+
Display::fmt(&esc, f)?;
24412438
f.write_char('\'')
24422439
}
24432440
}

0 commit comments

Comments
 (0)