Skip to content

Commit e86fd62

Browse files
committed
Auto merge of rust-lang#111524 - scottmcm:escape-using-ascii, r=cuviper
`ascii::Char`-ify the escaping code in `core` This means that `EscapeIterInner::as_str` no longer needs unsafe code, because the type system ensures the internal buffer is only ASCII, and thus valid UTF-8. Come to think of it, this also gives it a (non-guaranteed) niche. cc `@BurntSushi` as potentially interested `ascii::Char` tracking issue: rust-lang#110998
2 parents 7047d97 + 28449da commit e86fd62

File tree

5 files changed

+65
-50
lines changed

5 files changed

+65
-50
lines changed

library/core/src/ascii.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ pub struct EscapeDefault(escape::EscapeIterInner<4>);
9191
/// ```
9292
#[stable(feature = "rust1", since = "1.0.0")]
9393
pub fn escape_default(c: u8) -> EscapeDefault {
94-
let mut data = [0; 4];
94+
let mut data = [Char::Null; 4];
9595
let range = escape::escape_ascii_into(&mut data, c);
9696
EscapeDefault(escape::EscapeIterInner::new(data, range))
9797
}

library/core/src/char/methods.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -392,13 +392,13 @@ impl char {
392392
#[inline]
393393
pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
394394
match self {
395-
'\0' => EscapeDebug::backslash(b'0'),
396-
'\t' => EscapeDebug::backslash(b't'),
397-
'\r' => EscapeDebug::backslash(b'r'),
398-
'\n' => EscapeDebug::backslash(b'n'),
399-
'\\' => EscapeDebug::backslash(b'\\'),
400-
'"' if args.escape_double_quote => EscapeDebug::backslash(b'"'),
401-
'\'' if args.escape_single_quote => EscapeDebug::backslash(b'\''),
395+
'\0' => EscapeDebug::backslash(ascii::Char::Digit0),
396+
'\t' => EscapeDebug::backslash(ascii::Char::SmallT),
397+
'\r' => EscapeDebug::backslash(ascii::Char::SmallR),
398+
'\n' => EscapeDebug::backslash(ascii::Char::SmallN),
399+
'\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
400+
'\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
401+
'\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
402402
_ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
403403
EscapeDebug::from_unicode(self.escape_unicode())
404404
}
@@ -503,11 +503,11 @@ impl char {
503503
#[inline]
504504
pub fn escape_default(self) -> EscapeDefault {
505505
match self {
506-
'\t' => EscapeDefault::backslash(b't'),
507-
'\r' => EscapeDefault::backslash(b'r'),
508-
'\n' => EscapeDefault::backslash(b'n'),
509-
'\\' | '\'' | '"' => EscapeDefault::backslash(self as u8),
510-
'\x20'..='\x7e' => EscapeDefault::printable(self as u8),
506+
'\t' => EscapeDefault::backslash(ascii::Char::SmallT),
507+
'\r' => EscapeDefault::backslash(ascii::Char::SmallR),
508+
'\n' => EscapeDefault::backslash(ascii::Char::SmallN),
509+
'\\' | '\'' | '"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
510+
'\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
511511
_ => EscapeDefault::from_unicode(self.escape_unicode()),
512512
}
513513
}

library/core/src/char/mod.rs

+12-11
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ pub use self::methods::encode_utf16_raw;
3838
#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
3939
pub use self::methods::encode_utf8_raw;
4040

41+
use crate::ascii;
4142
use crate::error::Error;
4243
use crate::escape;
4344
use crate::fmt::{self, Write};
@@ -152,7 +153,7 @@ pub struct EscapeUnicode(escape::EscapeIterInner<10>);
152153

153154
impl EscapeUnicode {
154155
fn new(chr: char) -> Self {
155-
let mut data = [0; 10];
156+
let mut data = [ascii::Char::Null; 10];
156157
let range = escape::escape_unicode_into(&mut data, chr);
157158
Self(escape::EscapeIterInner::new(data, range))
158159
}
@@ -218,14 +219,14 @@ impl fmt::Display for EscapeUnicode {
218219
pub struct EscapeDefault(escape::EscapeIterInner<10>);
219220

220221
impl EscapeDefault {
221-
fn printable(chr: u8) -> Self {
222-
let data = [chr, 0, 0, 0, 0, 0, 0, 0, 0, 0];
223-
Self(escape::EscapeIterInner::new(data, 0..1))
222+
fn printable(chr: ascii::Char) -> Self {
223+
let data = [chr];
224+
Self(escape::EscapeIterInner::from_array(data))
224225
}
225226

226-
fn backslash(chr: u8) -> Self {
227-
let data = [b'\\', chr, 0, 0, 0, 0, 0, 0, 0, 0];
228-
Self(escape::EscapeIterInner::new(data, 0..2))
227+
fn backslash(chr: ascii::Char) -> Self {
228+
let data = [ascii::Char::ReverseSolidus, chr];
229+
Self(escape::EscapeIterInner::from_array(data))
229230
}
230231

231232
fn from_unicode(esc: EscapeUnicode) -> Self {
@@ -307,9 +308,9 @@ impl EscapeDebug {
307308
Self(EscapeDebugInner::Char(chr))
308309
}
309310

310-
fn backslash(chr: u8) -> Self {
311-
let data = [b'\\', chr, 0, 0, 0, 0, 0, 0, 0, 0];
312-
let iter = escape::EscapeIterInner::new(data, 0..2);
311+
fn backslash(chr: ascii::Char) -> Self {
312+
let data = [ascii::Char::ReverseSolidus, chr];
313+
let iter = escape::EscapeIterInner::from_array(data);
313314
Self(EscapeDebugInner::Bytes(iter))
314315
}
315316

@@ -318,7 +319,7 @@ impl EscapeDebug {
318319
}
319320

320321
fn clear(&mut self) {
321-
let bytes = escape::EscapeIterInner::new([0; 10], 0..0);
322+
let bytes = escape::EscapeIterInner::from_array([]);
322323
self.0 = EscapeDebugInner::Bytes(bytes);
323324
}
324325
}

library/core/src/escape.rs

+39-26
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,41 @@
11
//! Helper code for character escaping.
22
3+
use crate::ascii;
34
use crate::num::NonZeroUsize;
45
use crate::ops::Range;
56

6-
const HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
7+
const HEX_DIGITS: [ascii::Char; 16] = *b"0123456789abcdef".as_ascii().unwrap();
78

89
/// Escapes a byte into provided buffer; returns length of escaped
910
/// representation.
10-
pub(crate) fn escape_ascii_into(output: &mut [u8; 4], byte: u8) -> Range<u8> {
11+
pub(crate) fn escape_ascii_into(output: &mut [ascii::Char; 4], byte: u8) -> Range<u8> {
12+
#[inline]
13+
fn backslash(a: ascii::Char) -> ([ascii::Char; 4], u8) {
14+
([ascii::Char::ReverseSolidus, a, ascii::Char::Null, ascii::Char::Null], 2)
15+
}
16+
1117
let (data, len) = match byte {
12-
b'\t' => ([b'\\', b't', 0, 0], 2),
13-
b'\r' => ([b'\\', b'r', 0, 0], 2),
14-
b'\n' => ([b'\\', b'n', 0, 0], 2),
15-
b'\\' => ([b'\\', b'\\', 0, 0], 2),
16-
b'\'' => ([b'\\', b'\'', 0, 0], 2),
17-
b'"' => ([b'\\', b'"', 0, 0], 2),
18-
b'\x20'..=b'\x7e' => ([byte, 0, 0, 0], 1),
19-
_ => {
18+
b'\t' => backslash(ascii::Char::SmallT),
19+
b'\r' => backslash(ascii::Char::SmallR),
20+
b'\n' => backslash(ascii::Char::SmallN),
21+
b'\\' => backslash(ascii::Char::ReverseSolidus),
22+
b'\'' => backslash(ascii::Char::Apostrophe),
23+
b'\"' => backslash(ascii::Char::QuotationMark),
24+
_ => if let Some(a) = byte.as_ascii() && !byte.is_ascii_control() {
25+
([a, ascii::Char::Null, ascii::Char::Null, ascii::Char::Null], 1)
26+
} else {
2027
let hi = HEX_DIGITS[usize::from(byte >> 4)];
2128
let lo = HEX_DIGITS[usize::from(byte & 0xf)];
22-
([b'\\', b'x', hi, lo], 4)
29+
([ascii::Char::ReverseSolidus, ascii::Char::SmallX, hi, lo], 4)
2330
}
2431
};
2532
*output = data;
26-
0..(len as u8)
33+
0..len
2734
}
2835

2936
/// Escapes a character into provided buffer using `\u{NNNN}` representation.
30-
pub(crate) fn escape_unicode_into(output: &mut [u8; 10], ch: char) -> Range<u8> {
31-
output[9] = b'}';
37+
pub(crate) fn escape_unicode_into(output: &mut [ascii::Char; 10], ch: char) -> Range<u8> {
38+
output[9] = ascii::Char::RightCurlyBracket;
3239

3340
let ch = ch as u32;
3441
output[3] = HEX_DIGITS[((ch >> 20) & 15) as usize];
@@ -41,7 +48,8 @@ pub(crate) fn escape_unicode_into(output: &mut [u8; 10], ch: char) -> Range<u8>
4148
// or-ing 1 ensures that for ch==0 the code computes that one digit should
4249
// be printed.
4350
let start = (ch | 1).leading_zeros() as usize / 4 - 2;
44-
output[start..start + 3].copy_from_slice(b"\\u{");
51+
const UNICODE_ESCAPE_PREFIX: &[ascii::Char; 3] = b"\\u{".as_ascii().unwrap();
52+
output[start..][..3].copy_from_slice(UNICODE_ESCAPE_PREFIX);
4553

4654
(start as u8)..10
4755
}
@@ -52,41 +60,46 @@ pub(crate) fn escape_unicode_into(output: &mut [u8; 10], ch: char) -> Range<u8>
5260
/// limited to u8 to reduce size of the structure.
5361
#[derive(Clone, Debug)]
5462
pub(crate) struct EscapeIterInner<const N: usize> {
55-
// Invariant: data[alive] is all ASCII.
56-
pub(crate) data: [u8; N],
63+
// The element type ensures this is always ASCII, and thus also valid UTF-8.
64+
pub(crate) data: [ascii::Char; N],
5765

5866
// Invariant: alive.start <= alive.end <= N.
5967
pub(crate) alive: Range<u8>,
6068
}
6169

6270
impl<const N: usize> EscapeIterInner<N> {
63-
pub fn new(data: [u8; N], alive: Range<u8>) -> Self {
71+
pub fn new(data: [ascii::Char; N], alive: Range<u8>) -> Self {
6472
const { assert!(N < 256) };
6573
debug_assert!(alive.start <= alive.end && usize::from(alive.end) <= N, "{alive:?}");
66-
let this = Self { data, alive };
67-
debug_assert!(this.as_bytes().is_ascii(), "Expected ASCII, got {:?}", this.as_bytes());
68-
this
74+
Self { data, alive }
75+
}
76+
77+
pub fn from_array<const M: usize>(array: [ascii::Char; M]) -> Self {
78+
const { assert!(M <= N) };
79+
80+
let mut data = [ascii::Char::Null; N];
81+
data[..M].copy_from_slice(&array);
82+
Self::new(data, 0..M as u8)
6983
}
7084

71-
fn as_bytes(&self) -> &[u8] {
85+
pub fn as_ascii(&self) -> &[ascii::Char] {
7286
&self.data[usize::from(self.alive.start)..usize::from(self.alive.end)]
7387
}
7488

7589
pub fn as_str(&self) -> &str {
76-
// SAFETY: self.data[self.alive] is all ASCII characters.
77-
unsafe { crate::str::from_utf8_unchecked(self.as_bytes()) }
90+
self.as_ascii().as_str()
7891
}
7992

8093
pub fn len(&self) -> usize {
8194
usize::from(self.alive.end - self.alive.start)
8295
}
8396

8497
pub fn next(&mut self) -> Option<u8> {
85-
self.alive.next().map(|i| self.data[usize::from(i)])
98+
self.alive.next().map(|i| self.data[usize::from(i)].as_u8())
8699
}
87100

88101
pub fn next_back(&mut self) -> Option<u8> {
89-
self.alive.next_back().map(|i| self.data[usize::from(i)])
102+
self.alive.next_back().map(|i| self.data[usize::from(i)].as_u8())
90103
}
91104

92105
pub fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> {

library/core/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@
216216
#![feature(intra_doc_pointers)]
217217
#![feature(intrinsics)]
218218
#![feature(lang_items)]
219+
#![feature(let_chains)]
219220
#![feature(link_llvm_intrinsics)]
220221
#![feature(macro_metavar_expr)]
221222
#![feature(min_specialization)]

0 commit comments

Comments
 (0)