1use 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#[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#[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#[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#[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 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 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 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 let lookup_escaped = lookup & 0x80 != 0;
121
122 let lookup_ascii = unsafe { ascii::Char::from_u8_unchecked(lookup & 0x7F) };
124
125 if lookup_escaped {
126 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#[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 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#[ferrocene::prevalidated]
176#[derive(Clone, Copy)]
177pub(crate) struct AlwaysEscaped;
178
179#[ferrocene::prevalidated]
182#[derive(Clone, Copy)]
183pub(crate) struct MaybeEscaped;
184
185#[derive(Clone)]
187#[ferrocene::prevalidated]
188pub(crate) struct EscapeIterInner<const N: usize, ESCAPING> {
189 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 #[inline]
209 #[ferrocene::prevalidated]
210 const unsafe fn new(data: MaybeEscapedCharacter<N>, alive: Range<u8>) -> Self {
211 const { assert!(N < Self::LITERAL_ESCAPE_START as usize) };
214
215 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 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 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 unsafe { Self::new(MaybeEscapedCharacter { escape_seq }, alive) }
241 }
242
243 #[inline]
244 #[ferrocene::prevalidated]
245 pub(crate) const fn empty() -> Self {
246 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 #[inline]
269 #[ferrocene::prevalidated]
270 const fn to_char(&self) -> Option<char> {
271 if self.alive.end > Self::LITERAL_ESCAPE_START {
272 return Some(unsafe { self.data.literal });
275 }
276
277 None
278 }
279
280 #[inline]
288 #[ferrocene::prevalidated]
289 unsafe fn to_str_unchecked(&self) -> &str {
290 debug_assert!(self.alive.end <= Self::LITERAL_ESCAPE_START);
291
292 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 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 unsafe { Some(self.data.escape_seq.get_unchecked(usize::from(i)).to_u8()) }
325 }
326}
327
328impl<const N: usize> EscapeIterInner<N, MaybeEscaped> {
329 #[ferrocene::prevalidated]
334 pub(crate) const fn printable(c: char) -> Self {
335 Self {
336 data: MaybeEscapedCharacter { literal: c },
337 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 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 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 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}