Skip to content

Commit

Permalink
Rollup merge of #94776 - martingms:optimize-escape-default, r=nnether…
Browse files Browse the repository at this point in the history
…cote

Optimize ascii::escape_default

`ascii::escape_default` showed up as a hot function when compiling `deunicode-1.3.1` in `@nnethercote's` [analysis](https://hackmd.io/mxdn4U58Su-UQXwzOHpHag) of `@lqd's` [rustc-benchmarking-data](https://github.com/lqd/rustc-benchmarking-data).
After taking a look at the generated assembly it looked like a LUT-based approach could be faster for `hexify()`-ing ascii characters, so that's what this PR implements

The patch looks like it provides about a 1-2% improvement in instructions for that particular crate. This should definitely be verified with a perf run as I'm still getting used to the `rustc-perf` tooling and might easily have made an error!
  • Loading branch information
Dylan-DPC authored Mar 11, 2022
2 parents b711d17 + c62ab42 commit cdd6d39
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions library/core/src/ascii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,22 +98,20 @@ pub fn escape_default(c: u8) -> EscapeDefault {
b'\'' => ([b'\\', b'\'', 0, 0], 2),
b'"' => ([b'\\', b'"', 0, 0], 2),
b'\x20'..=b'\x7e' => ([c, 0, 0, 0], 1),
_ => ([b'\\', b'x', hexify(c >> 4), hexify(c & 0xf)], 4),
_ => {
let hex_digits: &[u8; 16] = b"0123456789abcdef";
([b'\\', b'x', hex_digits[(c >> 4) as usize], hex_digits[(c & 0xf) as usize]], 4)
}
};

return EscapeDefault { range: 0..len, data };

fn hexify(b: u8) -> u8 {
match b {
0..=9 => b'0' + b,
_ => b'a' + b - 10,
}
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Iterator for EscapeDefault {
type Item = u8;

#[inline]
fn next(&mut self) -> Option<u8> {
self.range.next().map(|i| self.data[i as usize])
}
Expand Down

0 comments on commit cdd6d39

Please sign in to comment.