Skip to main content

core/
escape.rs

1//! Helper code for character escaping.
2
3use crate::ascii;
4use crate::fmt::{self, Write};
5use crate::marker::PhantomData;
6use crate::num::NonZero;
7use crate::ops::Range;
8
9const HEX_DIGITS: [ascii::Char; 16] = *b"0123456789abcdef".as_ascii().unwrap();
10
11/// Escapes a character with `\x` representation.
12///
13/// Returns a buffer with the escaped representation and its corresponding range.
14#[inline]
15#[ferrocene::prevalidated]
16const fn backslash<const N: usize>(a: ascii::Char) -> ([ascii::Char; N], Range<u8>) {
17    const { assert!(N >= 2) };
18
19    let mut output = [ascii::Char::Null; N];
20
21    output[0] = ascii::Char::ReverseSolidus;
22    output[1] = a;
23
24    (output, 0..2)
25}
26
27/// Escapes a character with `\xNN` representation.
28///
29/// Returns a buffer with the escaped representation and its corresponding range.
30#[inline]
31#[ferrocene::prevalidated]
32const fn hex_escape<const N: usize>(byte: u8) -> ([ascii::Char; N], Range<u8>) {
33    const { assert!(N >= 4) };
34
35    let mut output = [ascii::Char::Null; N];
36
37    let hi = HEX_DIGITS[(byte >> 4) as usize];
38    let lo = HEX_DIGITS[(byte & 0xf) as usize];
39
40    output[0] = ascii::Char::ReverseSolidus;
41    output[1] = ascii::Char::SmallX;
42    output[2] = hi;
43    output[3] = lo;
44
45    (output, 0..4)
46}
47
48/// Returns a buffer with the verbatim character and its corresponding range.
49#[inline]
50#[ferrocene::prevalidated]
51const fn verbatim<const N: usize>(a: ascii::Char) -> ([ascii::Char; N], Range<u8>) {
52    const { assert!(N >= 1) };
53
54    let mut output = [ascii::Char::Null; N];
55
56    output[0] = a;
57
58    (output, 0..1)
59}
60
61/// Escapes an ASCII character.
62///
63/// Returns a buffer with the escaped representation and its corresponding range.
64#[ferrocene::prevalidated]
65const fn escape_ascii<const N: usize>(byte: u8) -> ([ascii::Char; N], Range<u8>) {
66    const { assert!(N >= 4) };
67
68    #[cfg(feature = "optimize_for_size")]
69    {
70        match byte {
71            b'\t' => backslash(ascii::Char::SmallT),
72            b'\r' => backslash(ascii::Char::SmallR),
73            b'\n' => backslash(ascii::Char::SmallN),
74            b'\\' => backslash(ascii::Char::ReverseSolidus),
75            b'\'' => backslash(ascii::Char::Apostrophe),
76            b'"' => backslash(ascii::Char::QuotationMark),
77            0x00..=0x1F | 0x7F => hex_escape(byte),
78            _ => match ascii::Char::from_u8(byte) {
79                Some(a) => verbatim(a),
80                None => hex_escape(byte),
81            },
82        }
83    }
84
85    #[cfg(not(feature = "optimize_for_size"))]
86    {
87        /// Lookup table helps us determine how to display character.
88        ///
89        /// Since ASCII characters will always be 7 bits, we can exploit this to store the 8th bit to
90        /// indicate whether the result is escaped or unescaped.
91        ///
92        /// We additionally use 0x80 (escaped NUL character) to indicate hex-escaped bytes, since
93        /// escaped NUL will not occur.
94        const LOOKUP: [u8; 256] = {
95            let mut arr = [0; 256];
96            let mut idx = 0;
97            while idx <= 255 {
98                arr[idx] = match idx as u8 {
99                    // use 8th bit to indicate escaped
100                    b'\t' => 0x80 | b't',
101                    b'\r' => 0x80 | b'r',
102                    b'\n' => 0x80 | b'n',
103                    b'\\' => 0x80 | b'\\',
104                    b'\'' => 0x80 | b'\'',
105                    b'"' => 0x80 | b'"',
106
107                    // use NUL to indicate hex-escaped
108                    0x00..=0x1F | 0x7F..=0xFF => 0x80 | b'\0',
109
110                    idx => idx,
111                };
112                idx += 1;
113            }
114            arr
115        };
116
117        let lookup = LOOKUP[byte as usize];
118
119        // 8th bit indicates escape
120        let lookup_escaped = lookup & 0x80 != 0;
121
122        // SAFETY: We explicitly mask out the eighth bit to get a 7-bit ASCII character.
123        let lookup_ascii = unsafe { ascii::Char::from_u8_unchecked(lookup & 0x7F) };
124
125        if lookup_escaped {
126            // NUL indicates hex-escaped
127            if matches!(lookup_ascii, ascii::Char::Null) {
128                hex_escape(byte)
129            } else {
130                backslash(lookup_ascii)
131            }
132        } else {
133            verbatim(lookup_ascii)
134        }
135    }
136}
137
138/// Escapes a character with `\u{NNNN}` representation.
139///
140/// Returns a buffer with the escaped representation and its corresponding range.
141#[ferrocene::prevalidated]
142const fn escape_unicode<const N: usize>(c: char) -> ([ascii::Char; N], Range<u8>) {
143    const { assert!(N >= 10 && N < u8::MAX as usize) };
144
145    let c = c as u32;
146
147    // OR-ing `1` ensures that for `c == 0` the code computes that
148    // one digit should be printed.
149    let start = (c | 1).leading_zeros() as usize / 4 - 2;
150
151    let mut output = [ascii::Char::Null; N];
152    output[3] = HEX_DIGITS[((c >> 20) & 15) as usize];
153    output[4] = HEX_DIGITS[((c >> 16) & 15) as usize];
154    output[5] = HEX_DIGITS[((c >> 12) & 15) as usize];
155    output[6] = HEX_DIGITS[((c >> 8) & 15) as usize];
156    output[7] = HEX_DIGITS[((c >> 4) & 15) as usize];
157    output[8] = HEX_DIGITS[((c >> 0) & 15) as usize];
158    output[9] = ascii::Char::RightCurlyBracket;
159    output[start + 0] = ascii::Char::ReverseSolidus;
160    output[start + 1] = ascii::Char::SmallU;
161    output[start + 2] = ascii::Char::LeftCurlyBracket;
162
163    (output, (start as u8)..(N as u8))
164}
165
166#[derive(Clone, Copy)]
167#[ferrocene::prevalidated]
168union MaybeEscapedCharacter<const N: usize> {
169    pub escape_seq: [ascii::Char; N],
170    pub literal: char,
171}
172
173/// Marker type to indicate that the character is always escaped,
174/// used to optimize the iterator implementation.
175#[ferrocene::prevalidated]
176#[derive(Clone, Copy)]
177pub(crate) struct AlwaysEscaped;
178
179/// Marker type to indicate that the character may be escaped,
180/// used to optimize the iterator implementation.
181#[ferrocene::prevalidated]
182#[derive(Clone, Copy)]
183pub(crate) struct MaybeEscaped;
184
185/// An iterator over a possibly escaped character.
186#[derive(Clone)]
187#[ferrocene::prevalidated]
188pub(crate) struct EscapeIterInner<const N: usize, ESCAPING> {
189    // Invariant:
190    //
191    // If `alive.end <= Self::LITERAL_ESCAPE_START`, `data` must contain
192    // printable ASCII characters in the `alive` range of its `escape_seq` variant.
193    //
194    // If `alive.end > Self::LITERAL_ESCAPE_START`, `data` must contain a
195    // `char` in its `literal` variant, and the `alive` range must have a
196    // length of at most `1`.
197    data: MaybeEscapedCharacter<N>,
198    alive: Range<u8>,
199    escaping: PhantomData<ESCAPING>,
200}
201
202impl<const N: usize, ESCAPING> EscapeIterInner<N, ESCAPING> {
203    const LITERAL_ESCAPE_START: u8 = 128;
204
205    /// # Safety
206    ///
207    /// `data.escape_seq` must contain an escape sequence in the range given by `alive`.
208    #[inline]
209    #[ferrocene::prevalidated]
210    const unsafe fn new(data: MaybeEscapedCharacter<N>, alive: Range<u8>) -> Self {
211        // Longer escape sequences are not useful given `alive.end` is at most
212        // `Self::LITERAL_ESCAPE_START`.
213        const { assert!(N < Self::LITERAL_ESCAPE_START as usize) };
214
215        // Check bounds, which implicitly also checks the invariant
216        // `alive.end <= Self::LITERAL_ESCAPE_START`.
217        debug_assert!(alive.end <= (N + 1) as u8);
218
219        Self { data, alive, escaping: PhantomData }
220    }
221
222    #[ferrocene::prevalidated]
223    pub(crate) const fn backslash(c: ascii::Char) -> Self {
224        let (escape_seq, alive) = backslash(c);
225        // SAFETY: `escape_seq` contains an escape sequence in the range given by `alive`.
226        unsafe { Self::new(MaybeEscapedCharacter { escape_seq }, alive) }
227    }
228
229    #[ferrocene::prevalidated]
230    pub(crate) const fn ascii(c: u8) -> Self {
231        let (escape_seq, alive) = escape_ascii(c);
232        // SAFETY: `escape_seq` contains an escape sequence in the range given by `alive`.
233        unsafe { Self::new(MaybeEscapedCharacter { escape_seq }, alive) }
234    }
235
236    #[ferrocene::prevalidated]
237    pub(crate) const fn unicode(c: char) -> Self {
238        let (escape_seq, alive) = escape_unicode(c);
239        // SAFETY: `escape_seq` contains an escape sequence in the range given by `alive`.
240        unsafe { Self::new(MaybeEscapedCharacter { escape_seq }, alive) }
241    }
242
243    #[inline]
244    #[ferrocene::prevalidated]
245    pub(crate) const fn empty() -> Self {
246        // SAFETY: `0..0` ensures an empty escape sequence.
247        unsafe { Self::new(MaybeEscapedCharacter { escape_seq: [ascii::Char::Null; N] }, 0..0) }
248    }
249
250    #[inline]
251    #[ferrocene::prevalidated]
252    pub(crate) fn len(&self) -> usize {
253        usize::from(self.alive.end - self.alive.start)
254    }
255
256    #[inline]
257    #[ferrocene::prevalidated]
258    pub(crate) fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
259        self.alive.advance_by(n)
260    }
261
262    #[inline]
263    pub(crate) fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
264        self.alive.advance_back_by(n)
265    }
266
267    /// Returns a `char` if `self.data` contains one in its `literal` variant.
268    #[inline]
269    #[ferrocene::prevalidated]
270    const fn to_char(&self) -> Option<char> {
271        if self.alive.end > Self::LITERAL_ESCAPE_START {
272            // SAFETY: We just checked that `self.data` contains a `char` in
273            //         its `literal` variant.
274            return Some(unsafe { self.data.literal });
275        }
276
277        None
278    }
279
280    /// Returns the printable ASCII characters in the `escape_seq` variant of `self.data`
281    /// as a string.
282    ///
283    /// # Safety
284    ///
285    /// - `self.data` must contain printable ASCII characters in its `escape_seq` variant.
286    /// - `self.alive` must be a valid range for `self.data.escape_seq`.
287    #[inline]
288    #[ferrocene::prevalidated]
289    unsafe fn to_str_unchecked(&self) -> &str {
290        debug_assert!(self.alive.end <= Self::LITERAL_ESCAPE_START);
291
292        // SAFETY: The caller guarantees `self.data` contains printable ASCII
293        //         characters in its `escape_seq` variant, and `self.alive` is
294        //         a valid range for `self.data.escape_seq`.
295        unsafe {
296            self.data
297                .escape_seq
298                .get_unchecked(usize::from(self.alive.start)..usize::from(self.alive.end))
299                .as_str()
300        }
301    }
302}
303
304impl<const N: usize> EscapeIterInner<N, AlwaysEscaped> {
305    #[ferrocene::prevalidated]
306    pub(crate) fn next(&mut self) -> Option<u8> {
307        let i = self.alive.next()?;
308
309        // SAFETY: The `AlwaysEscaped` marker guarantees that `self.data`
310        //         contains printable ASCII characters in its `escape_seq`
311        //         variant, and `i` is guaranteed to be a valid index for
312        //         `self.data.escape_seq`.
313        unsafe { Some(self.data.escape_seq.get_unchecked(usize::from(i)).to_u8()) }
314    }
315
316    #[ferrocene::prevalidated]
317    pub(crate) fn next_back(&mut self) -> Option<u8> {
318        let i = self.alive.next_back()?;
319
320        // SAFETY: The `AlwaysEscaped` marker guarantees that `self.data`
321        //         contains printable ASCII characters in its `escape_seq`
322        //         variant, and `i` is guaranteed to be a valid index for
323        //         `self.data.escape_seq`.
324        unsafe { Some(self.data.escape_seq.get_unchecked(usize::from(i)).to_u8()) }
325    }
326}
327
328impl<const N: usize> EscapeIterInner<N, MaybeEscaped> {
329    // This is the only way to create any `EscapeIterInner` containing a `char` in
330    // the `literal` variant of its `self.data`, meaning the `AlwaysEscaped` marker
331    // guarantees that `self.data` contains printable ASCII characters in its
332    // `escape_seq` variant.
333    #[ferrocene::prevalidated]
334    pub(crate) const fn printable(c: char) -> Self {
335        Self {
336            data: MaybeEscapedCharacter { literal: c },
337            // Uphold the invariant `alive.end > Self::LITERAL_ESCAPE_START`, and ensure
338            // `len` behaves correctly for iterating through one character literal.
339            alive: Self::LITERAL_ESCAPE_START..(Self::LITERAL_ESCAPE_START + 1),
340            escaping: PhantomData,
341        }
342    }
343
344    #[ferrocene::prevalidated]
345    pub(crate) fn next(&mut self) -> Option<char> {
346        let i = self.alive.next()?;
347
348        if let Some(c) = self.to_char() {
349            return Some(c);
350        }
351
352        // SAFETY: At this point, `self.data` must contain printable ASCII
353        //         characters in its `escape_seq` variant, and `i` is
354        //         guaranteed to be a valid index for `self.data.escape_seq`.
355        Some(char::from(unsafe { self.data.escape_seq.get_unchecked(usize::from(i)).to_u8() }))
356    }
357}
358
359impl<const N: usize> fmt::Display for EscapeIterInner<N, AlwaysEscaped> {
360    #[ferrocene::prevalidated]
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        // SAFETY: The `AlwaysEscaped` marker guarantees that `self.data`
363        //         contains printable ASCII chars, and `self.alive` is
364        //         guaranteed to be a valid range for `self.data`.
365        f.write_str(unsafe { self.to_str_unchecked() })
366    }
367}
368
369impl<const N: usize> fmt::Display for EscapeIterInner<N, MaybeEscaped> {
370    #[ferrocene::prevalidated]
371    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372        if let Some(c) = self.to_char() {
373            return if self.alive.is_empty() { Ok(()) } else { f.write_char(c) };
374        }
375
376        // SAFETY: At this point, `self.data` must contain printable ASCII
377        //         characters in its `escape_seq` variant, and `self.alive`
378        //         is guaranteed to be a valid range for `self.data`.
379        f.write_str(unsafe { self.to_str_unchecked() })
380    }
381}
382
383impl<const N: usize> fmt::Debug for EscapeIterInner<N, AlwaysEscaped> {
384    #[ferrocene::prevalidated]
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        f.debug_tuple("EscapeIterInner").field(&format_args!("'{}'", self)).finish()
387    }
388}
389
390impl<const N: usize> fmt::Debug for EscapeIterInner<N, MaybeEscaped> {
391    #[ferrocene::prevalidated]
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        f.debug_tuple("EscapeIterInner").field(&format_args!("'{}'", self)).finish()
394    }
395}