Skip to content

Commit aaba972

Browse files
committed
Switch to primarily using &str
Surprisingly, benchmarks have shown that using `&str` instead of `&[u8]` with some `unsafe` code is actually faster.
1 parent 42d870e commit aaba972

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

library/core/src/fmt/mod.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -2409,9 +2409,10 @@ impl Debug for str {
24092409

24102410
// the outer loop here splits the string into chunks of printable ASCII, which is just skipped over,
24112411
// and chunks of other chars (unicode, or ASCII that needs escaping), which is handler per-`char`.
2412-
let mut rest = self.as_bytes();
2412+
let mut rest = self;
24132413
while rest.len() > 0 {
2414-
let Some(non_printable_start) = rest.iter().position(|&b| needs_escape(b)) else {
2414+
let Some(non_printable_start) = rest.as_bytes().iter().position(|&b| needs_escape(b))
2415+
else {
24152416
printable_range.end += rest.len();
24162417
break;
24172418
};
@@ -2420,12 +2421,10 @@ impl Debug for str {
24202421
// SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
24212422
rest = unsafe { rest.get_unchecked(non_printable_start..) };
24222423

2423-
let printable_start = rest.iter().position(|&b| !needs_escape(b)).unwrap_or(rest.len());
2424+
let printable_start =
2425+
rest.as_bytes().iter().position(|&b| !needs_escape(b)).unwrap_or(rest.len());
24242426
let prefix;
2425-
// SAFETY: the position was derived from an iterator, so is known to be within bounds, and at a char boundary
2426-
(prefix, rest) = unsafe { rest.split_at_unchecked(printable_start) };
2427-
// SAFETY: prefix is a valid utf8 sequence, and at a char boundary
2428-
let prefix = unsafe { crate::str::from_utf8_unchecked(prefix) };
2427+
(prefix, rest) = rest.split_at(printable_start);
24292428

24302429
for c in prefix.chars() {
24312430
let esc = c.escape_debug_ext(EscapeDebugExtArgs {

0 commit comments

Comments
 (0)