Skip to content

Commit 24b5d3a

Browse files
committed
Improve speed of fmt::Debug for str and char
fixes rust-lang#26920
1 parent 5ca60d9 commit 24b5d3a

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

src/libcore/char.rs

+10
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ pub trait CharExt {
147147
fn to_digit(self, radix: u32) -> Option<u32>;
148148
fn escape_unicode(self) -> EscapeUnicode;
149149
fn escape_default(self) -> EscapeDefault;
150+
fn needs_escape_default(self) -> bool;
150151
fn len_utf8(self) -> usize;
151152
fn len_utf16(self) -> usize;
152153
fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>;
@@ -194,6 +195,15 @@ impl CharExt for char {
194195
EscapeDefault { state: init_state }
195196
}
196197

198+
#[inline]
199+
fn needs_escape_default(self) -> bool {
200+
match self {
201+
'\\' | '\'' | '"' => true,
202+
'\x20' ... '\x7e' => false,
203+
_ => true
204+
}
205+
}
206+
197207
#[inline]
198208
fn len_utf8(self) -> usize {
199209
let code = self as u32;

src/libcore/fmt/mod.rs

+15-7
Original file line numberDiff line numberDiff line change
@@ -1310,11 +1310,20 @@ impl Display for bool {
13101310
#[stable(feature = "rust1", since = "1.0.0")]
13111311
impl Debug for str {
13121312
fn fmt(&self, f: &mut Formatter) -> Result {
1313-
try!(write!(f, "\""));
1314-
for c in self.chars().flat_map(|c| c.escape_default()) {
1315-
try!(f.write_char(c))
1313+
try!(f.write_char('"'));
1314+
let mut from = 0;
1315+
for (i, c) in self.char_indices() {
1316+
// If char needs escaping, flush backlog so far and write, else skip
1317+
if c.needs_escape_default() {
1318+
try!(f.write_str(&self[from..i]));
1319+
for e in c.escape_default() {
1320+
try!(f.write_char(e));
1321+
}
1322+
from = i + c.len_utf8();
1323+
}
13161324
}
1317-
write!(f, "\"")
1325+
try!(f.write_str(&self[from..]));
1326+
f.write_char('"')
13181327
}
13191328
}
13201329

@@ -1328,12 +1337,11 @@ impl Display for str {
13281337
#[stable(feature = "rust1", since = "1.0.0")]
13291338
impl Debug for char {
13301339
fn fmt(&self, f: &mut Formatter) -> Result {
1331-
use char::CharExt;
1332-
try!(write!(f, "'"));
1340+
try!(f.write_char('\''));
13331341
for c in self.escape_default() {
13341342
try!(f.write_char(c))
13351343
}
1336-
write!(f, "'")
1344+
f.write_char('\'')
13371345
}
13381346
}
13391347

0 commit comments

Comments
 (0)