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