Skip to content

Commit

Permalink
Optimize ascii::escape_default by using a digit LUT
Browse files Browse the repository at this point in the history
  • Loading branch information
martingms committed Mar 9, 2022
1 parent 10dccdc commit 8761424
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions library/core/src/ascii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,23 @@ 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 (b1, b2) = hexify(c);
([b'\\', b'x', b1, b2], 4)
}
};

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

fn hexify(b: u8) -> u8 {
match b {
0..=9 => b'0' + b,
_ => b'a' + b - 10,
#[inline]
fn hexify(b: u8) -> (u8, u8) {
let hex_digits: &[u8; 16] = b"0123456789abcdef";
// SAFETY: For all n: u8, n >> 4 < 16 and n & 0xf < 16
unsafe {
(
*hex_digits.get_unchecked((b >> 4) as usize),
*hex_digits.get_unchecked((b & 0xf) as usize),
)
}
}
}
Expand Down

0 comments on commit 8761424

Please sign in to comment.