Skip to content

Commit 6bfb89d

Browse files
committed
Optimize escape_ascii.
1 parent 474bee7 commit 6bfb89d

File tree

1 file changed

+25
-26
lines changed

1 file changed

+25
-26
lines changed

library/core/src/escape.rs

+25-26
Original file line numberDiff line numberDiff line change
@@ -24,32 +24,31 @@ const fn backslash<const N: usize>(a: ascii::Char) -> ([ascii::Char; N], Range<u
2424
const fn escape_ascii<const N: usize>(byte: u8) -> ([ascii::Char; N], Range<u8>) {
2525
const { assert!(N >= 4) };
2626

27-
match byte {
28-
b'\t' => backslash(ascii::Char::SmallT),
29-
b'\r' => backslash(ascii::Char::SmallR),
30-
b'\n' => backslash(ascii::Char::SmallN),
31-
b'\\' => backslash(ascii::Char::ReverseSolidus),
32-
b'\'' => backslash(ascii::Char::Apostrophe),
33-
b'\"' => backslash(ascii::Char::QuotationMark),
34-
byte => {
35-
let mut output = [ascii::Char::Null; N];
36-
37-
if let Some(c) = byte.as_ascii()
38-
&& !byte.is_ascii_control()
39-
{
40-
output[0] = c;
41-
(output, 0..1)
42-
} else {
43-
let hi = HEX_DIGITS[(byte >> 4) as usize];
44-
let lo = HEX_DIGITS[(byte & 0xf) as usize];
45-
46-
output[0] = ascii::Char::ReverseSolidus;
47-
output[1] = ascii::Char::SmallX;
48-
output[2] = hi;
49-
output[3] = lo;
50-
51-
(output, 0..4)
52-
}
27+
let mut output = [ascii::Char::Null; N];
28+
29+
match byte.as_ascii() {
30+
Some(
31+
c @ ascii::Char::CharacterTabulation
32+
| c @ ascii::Char::CarriageReturn
33+
| c @ ascii::Char::LineFeed
34+
| c @ ascii::Char::ReverseSolidus
35+
| c @ ascii::Char::Apostrophe
36+
| c @ ascii::Char::QuotationMark,
37+
) => backslash(c),
38+
Some(c) if !byte.is_ascii_control() => {
39+
output[0] = c;
40+
(output, 0..1)
41+
}
42+
_ => {
43+
let hi = HEX_DIGITS[(byte >> 4) as usize];
44+
let lo = HEX_DIGITS[(byte & 0xf) as usize];
45+
46+
output[0] = ascii::Char::ReverseSolidus;
47+
output[1] = ascii::Char::SmallX;
48+
output[2] = hi;
49+
output[3] = lo;
50+
51+
(output, 0..4)
5352
}
5453
}
5554
}

0 commit comments

Comments
 (0)