Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize ascii::escape_default #94776

Merged
merged 3 commits into from
Mar 11, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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),
)
}
Copy link
Contributor

@paolobarbolini paolobarbolini Mar 9, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drive by review: this might do without use of unsafe

https://rust.godbolt.org/z/5q3cW1Gox

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, thanks, I didn't even try that, I've yet to get a good feeling for what gets optimized and not. I'll do a local perf run with that and see if there's any changes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You were right of course, addressed in 7f4f4fc

}
}
Expand Down