Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![no_std]
2 #![forbid(unsafe_code)]
3 #![warn(clippy::pedantic, clippy::perf, missing_docs, clippy::panic, clippy::cargo)]
4 #![allow(clippy::type_complexity)]
5 #![cfg_attr(docsrs, feature(doc_cfg))]
6
7
8 /*!
9
10 # descape
11
12 Provides utilities for easily parsing escape sequences in a string via [`UnescapeExt`], using [`alloc::borrow::Cow`] to only borrow when needed.
13
14 This library supports many escape sequences:
15 - `\\a` -> `\x07`
16 - `\\b` -> `\x08`
17 - `\\t` -> `\x09`
18 - `\\n` -> `\x0A`
19 - `\\v` -> `\x0B`
20 - `\\f` -> `\x0C`
21 - `\\r` -> `\x0D`
22 - `\\e` -> `\x1B`
23 - `\\'` -> `'`
24 - `\\"` -> `"`
25 - <code>&bsol;&bsol;&grave;</code> -> <code>&grave;</code>
26 - `\\\\` -> `\\`
27 - `\\xNN` -> `\xNN`
28 - `\\o` -> `\o`, for all octal digits `o`
29 - `\\oo` -> `\oo`, for all octal digits `o`
30 - `\\ooo` -> `\ooo`, for all octal digits `o`
31 - `\\uXXXX` -> `\u{XXXX}`
32 - `\\u{HEX}` -> `\u{HEX}`
33
34 Along with this, you can define your own custom escape handlers! See [`UnescapeExt::to_unescaped_with`] for more information on that.
35
36 This crate supports `no-std`.
37
38 Optionally, this crate has the `std` and `core_error` features,
39 to allow the error type of an invalid escape to implement the `Error` trait.
40
41 `std` uses `std::error::Error`, and `core_error` depends on `core::error::Error`, which is stable on Rust 1.82.0 or greater.
42
43 */
44
45
46 #[cfg(any(feature = "std", docsrs))]
47 extern crate std;
48 #[cfg(any(feature = "std", docsrs))]
49 use std::error::Error as ErrorTrait;
50 #[cfg(all(feature = "core_error", not(feature = "std")))]
51 use core::error::Error as ErrorTrait;
52
53 extern crate alloc;
54
55 use alloc::{
56 borrow::Cow,
57 string::String,
58 str::CharIndices
59 };
60
61 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
62 /// An error representing an invalid escape sequence in a string.
63 pub struct InvalidEscape {
64 /// The index of the invalid escape sequence.
65 pub index: usize,
66 }
67
68 impl InvalidEscape {
69 /// Constructs an invalid escape error from an index.
70 #[must_use]
71 pub const fn new(index: usize) -> Self {
72 Self { index }
73 }
74 }
75
76 impl core::fmt::Display for InvalidEscape {
77 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78 write!(f, "invalid escape sequence at index {}", self.index)?;
79 Ok(())
80 }
81 }
82
83 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "core_error"))))]
84 #[cfg(any(feature = "std", feature = "core_error", docsrs))]
85 impl ErrorTrait for InvalidEscape {}
86
87 /// An enum defining all possible non-error returns for a macro.
88 #[derive(Debug, Clone, PartialEq, Eq)]
89 pub enum EscapeValue<'s> {
90 /// Remove the escape sequence entirely.
91 Remove,
92 /// Leave the escape sequence as is.
93 Skip,
94 /// Replace the escape sequence with a single character.
95 Character(char),
96 /// Replace the escape sequence with a string of characters.
97 String(Cow<'s, str>)
98 }
99
100 impl From<char> for EscapeValue<'static> {
101 fn from(value: char) -> Self {
102 Self::Character(value)
103 }
104 }
105
106 impl<'string> From<&'string str> for EscapeValue<'string> {
107 fn from(value: &'string str) -> Self {
108 Self::String(Cow::Borrowed(value))
109 }
110 }
111
112 impl<'string> From<Cow<'string, str>> for EscapeValue<'string> {
113 fn from(value: Cow<'string, str>) -> Self {
114 Self::String(value)
115 }
116 }
117
118 impl<'string> From<String> for EscapeValue<'string> {
119 fn from(value: String) -> Self {
120 Self::String(Cow::Owned(value))
121 }
122 }
123
124 /// A trait distinguishing an object as a handler for custom escape sequences.
125 ///
126 /// For convenience, this trait is **automatically implemented** for all implementors of `FnMut` with the correct signature.
127 ///
128 pub trait EscapeHandler {
129 /// Definition of a custom escape handler.
130 ///
131 /// Custom escape handlers are called before parsing any escape sequences,
132 /// and are given 3 arguments:
133 /// - `idx`: The index of the current character (e.g. `Hello\nthere` gets `5`)
134 /// - `chr`: The current character in the string (e.g. `\\n` gets `'n'`)
135 /// - `iter`: A mutable reference to the underlying character iterator -
136 /// use this to get the rest of the string via `CharIndices::as_str`,
137 /// or get the next characters
138 ///
139 /// Handlers return a `Result<Option<char>, ()>`.
140 /// Returning `Ok(Some(char))` replaces the sequence with the given character,
141 /// returning `Ok(None)` removes the sequence entirely,
142 /// and returning `Err` errors the unescaping at the index of the escape sequence.
143 ///
144 ///
145 /// # Examples
146
147 /// ## Permitting any escape, handing it back raw
148 /// ```rust
149 /// # use descape::*; use std::str::CharIndices;
150 /// fn raw<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result<EscapeValue<'s>, ()> {
151 /// Ok(chr.into())
152 /// }
153
154 /// let escaped = r"\H\e\l\l\o \n \W\o\r\l\d";
155 /// let unescaped = escaped.to_unescaped_with(raw).unwrap();
156 /// assert_eq!(unescaped, "Hello n World");
157 /// ```
158
159 /// ## Removing escape sequences entirely
160 /// ```rust
161 /// # use descape::*; use std::str::CharIndices;
162 /// fn raw<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result<EscapeValue<'s>, ()> {
163 /// Ok(EscapeValue::Remove)
164 /// }
165
166 /// let escaped = r"What if I want a \nnewline?";
167 /// let unescaped = escaped.to_unescaped_with(raw).unwrap();
168 /// assert_eq!(unescaped, "What if I want a newline?");
169 /// ```
170
171 /// ## Replacing escape sequences with their character number
172 /// ```rust
173 /// # use descape::*; use std::str::CharIndices;
174 /// fn charnum<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result<EscapeValue<'s>, ()> {
175 /// Ok(format!("[{:02X}]", chr as u32).into())
176 /// }
177
178 /// let escaped = r"Well this\Ais a\Zthing.";
179 /// let unescaped = escaped.to_unescaped_with(charnum).unwrap();
180 /// assert_eq!(unescaped, "Well this[41]is a[5A]thing.");
181 /// ```
182
183 /// ## Not allowing escape sequences unsupported by Rust
184 /// ```rust
185 /// # use descape::*; use std::str::CharIndices;
186 /// fn rust_only<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result<EscapeValue<'s>, ()> {
187 /// match chr {
188 /// 'a' | 'b' | 'v' | 'f' | 'e' | '`' => Err(()),
189 /// _ => descape::DefaultEscapeHandler.escape(idx, chr, iter)
190 /// }
191 /// }
192
193 /// r"This is \nfine".to_unescaped_with(rust_only).expect(r"\n is valid");
194 /// r"This is not \fine".to_unescaped_with(rust_only).expect_err(r"\f is invalid");
195 /// ```
196
197 /// # An informal note
198 /// Ideally, this trait would return `Result<EscapeValue<'source>, Option<Box<dyn Error>>>`, but `Error` has only been in `core`
199 /// since Rust version `1.82.0`. Using it would bump the MSRV by a tremendous amount,
200 /// and as such it has been left out.
201 #[allow(clippy::result_unit_err, clippy::missing_errors_doc)]
202 fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result<EscapeValue<'source>, ()>;
203 /// The escape prefix to use for this handler.
204 /// Defaults to `\\`.
205 ///
206 /// # Examples
207 /// ```rust
208 /// # use descape::*; use std::str::CharIndices;
209 /// struct PercentEscape;
210 /// impl EscapeHandler for PercentEscape {
211 /// fn prefix(&self) -> char { '%' }
212 /// fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result<EscapeValue<'source>, ()> {
213 /// descape::DefaultEscapeHandler.escape(idx, chr, iter)
214 /// }
215 /// }
216 ///
217 /// assert_eq!(
218 /// r"Hello,%tworld!".to_unescaped_with(PercentEscape).unwrap(),
219 /// "Hello,\tworld!"
220 /// )
221 /// ```
222 fn prefix(&self) -> char { '\\' }
223 }
224
225 impl<F> EscapeHandler for F
226 where F: for<'iter, 'source> FnMut(usize, char, &'iter mut CharIndices<'source>) -> Result<EscapeValue<'source>, ()>
227 {
228 fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result<EscapeValue<'source>, ()> {
229 self(idx, chr, iter)
230 }
231 }
232
233 mod sealed {
234 pub trait Sealed {}
235 impl Sealed for str {}
236 }
237
238 /// An extension trait for [`&str`](str) to allow parsing escape sequences in strings, only copying when needed.
239 pub trait UnescapeExt: sealed::Sealed {
240
241 /**
242 Unescapes a string, returning an [`alloc::borrow::Cow`].
243 Will only allocate if the string has any escape sequences.
244
245 Uses [`crate::DefaultHandler`].
246
247 # Errors
248 Errors if there's an invalid escape sequence in the string.
249 Passes back the byte index of the invalid character.
250 */
251 fn to_unescaped(&self) -> Result<Cow<'_, str>, InvalidEscape>;
252 /**
253 Unescapes a string using a custom escape handler. See the documentation of [`crate::EscapeHandler`] for more details.
254
255 # Errors
256
257 Errors if there's an invalid escape sequence in the string.
258 Passes back the byte index of the invalid character.
259
260 */
261 fn to_unescaped_with(
262 &self,
263 callback: impl EscapeHandler
264 ) -> Result<Cow<'_, str>, InvalidEscape>;
265 }
266
267
268 impl UnescapeExt for str {
269 #[inline]
270 fn to_unescaped(&'_ self) -> Result<Cow<'_, str>, InvalidEscape> {
271 self.to_unescaped_with(DefaultEscapeHandler)
272 }
273
274 // Put this outside to prevent monomorphization bloat
275 fn to_unescaped_with(
276 &'_ self,
277 mut callback: impl EscapeHandler
278 ) -> Result<Cow<'_, str>, InvalidEscape> {
279 to_unescaped_with_mono(self, &mut callback)
280 }
281 }
282
283 fn to_unescaped_with_mono<'this, 'cb>(
284 this: &'this str,
285 callback: &'cb mut dyn EscapeHandler
286 ) -> Result<Cow<'this, str>, InvalidEscape> {
287 // Iterates over each character as a UTF-8 string slice
288 let mut iter = this.char_indices();
289 let mut seen: &'this str = "";
290 let mut owned = None::<String>;
291 let prefix = callback.prefix();
292
293 while let Some((index, chr)) = iter.next() {
294 if chr != prefix {
295 if let Some(owned) = &mut owned {
296 owned.push(chr);
297 } else {
298 seen = &this[..index + chr.len_utf8()];
299 }
300 continue;
301 }
302 if let Some((i, chr)) = iter.next() {
303 let res = callback.escape(index, chr, &mut iter)
304 .map_err(|()| InvalidEscape { index })?;
305 if res == EscapeValue::Skip && owned.is_none() {
306 seen = &this[..i + chr.len_utf8()];
307 continue;
308 }
309 let owned = owned.get_or_insert_with(|| seen.into());
310 match res {
311 EscapeValue::Character(c) => { owned.push(c); continue; },
312 EscapeValue::String(str) => { owned.push_str(&*str); continue; },
313 EscapeValue::Remove => { continue; },
314 EscapeValue::Skip => { owned.push(prefix); owned.push(chr); continue; }
315 }
316 } else {
317 // No matches found
318 return Err(InvalidEscape::new(index));
319 }
320 }
321
322 match owned {
323 Some(string) => Ok(Cow::Owned(string)),
324 None => Ok(Cow::Borrowed(this)),
325 }
326 }
327
328 /// The default escape sequence handler.
329 ///
330 /// The following escapes are valid:
331 /// - `\\a` -> `\x07`
332 /// - `\\b` -> `\x08`
333 /// - `\\t` -> `\x09`
334 /// - `\\n` -> `\x0A`
335 /// - `\\v` -> `\x0B`
336 /// - `\\f` -> `\x0C`
337 /// - `\\r` -> `\x0D`
338 /// - `\\e` -> `\x1B`
339 /// - `\\'` -> `'`
340 /// - `\\"` -> `"`
341 /// - <code>&bsol;&bsol;&grave;</code> -> <code>&grave;</code>
342 /// - `\\\\` -> `\\`
343 /// - `\\xNN` -> `\xNN`
344 /// - `\\o` -> `\o`, for all octal digits `o`
345 /// - `\\oo` -> `\oo`, for all octal digits `o`
346 /// - `\\ooo` -> `\ooo`, for all octal digits `o`
347 /// - `\\uXXXX` -> `\u{XXXX}`
348 /// - `\\u{HEX}` -> `\u{HEX}`
349 ///
350 pub struct DefaultEscapeHandler;
351
352 impl EscapeHandler for DefaultEscapeHandler {
353 fn escape<'iter, 'source>(&mut self, _idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result<EscapeValue<'source>, ()> {
354 Ok( match chr {
355 'a' => '\x07'.into(),
356 'b' => '\x08'.into(),
357 't' => '\x09'.into(),
358 'n' => '\x0A'.into(),
359 'v' => '\x0B'.into(),
360 'f' => '\x0C'.into(),
361 'r' => '\x0D'.into(),
362 'e' => '\x1B'.into(),
363 '`' => '`'.into(),
364 '\'' => '\''.into(),
365 '"' => '"'.into(),
366 '\\' => '\\'.into(),
367 'u' => {
368 let (chr, skip) = unescape_unicode(iter).ok_or(())?;
369 // Skip the needed amount of characters
370 for _ in 0..skip { iter.next(); }
371 chr.into()
372 },
373 'x' => {
374 // Skip two characters
375 let res = unescape_hex(iter).ok_or(())?;
376 iter.next();
377 iter.next();
378 res.into()
379 },
380 c if c.is_digit(8) => {
381 let (chr, skip) = unescape_oct(c, iter).ok_or(())?;
382 for _ in 0..skip { iter.next(); }
383 chr.into()
384 },
385 _ => return Err(()),
386 } )
387 }
388 }
389
390 fn unescape_unicode(
391 iter: &mut CharIndices
392 ) -> Option<(char, usize)> {
393 let string = iter.as_str();
394 let (_, next) = iter.next()?;
395 if next == '{' {
396 // \u{HEX}
397 let end = string[1 ..].find('}')?;
398 let num = &string[1 ..= end];
399 let codepoint = u32::from_str_radix(num, 16).ok()?;
400 char::from_u32(codepoint).map(|v| (v, end + 1))
401 } else {
402 // \uNNNN
403 // If any of these are non-ASCII, then it's already invalid,
404 // so a direct slice is fine
405 let next_four = string.get( ..4 )?;
406 let codepoint = u32::from_str_radix(next_four, 16).ok()?;
407 // Encode the u32
408 char::from_u32(codepoint).map(|v| (v, 3))
409 }
410 }
411
412 // FIXME: This could be factored out along with part of unescape_unicode into its own function.
413 fn unescape_hex(
414 iter: &mut CharIndices
415 ) -> Option<char> {
416
417 // Must be \xNN
418 let codepoint = iter.as_str()
419 .get(..2)
420 .and_then(|num| u32::from_str_radix(num, 16).ok())?;
421 char::from_u32(codepoint)
422 }
423
424 #[allow(clippy::cast_possible_truncation)] // Can't actually happen
425 fn unescape_oct(
426 chr: char,
427 iter: &mut CharIndices
428 ) -> Option<(char, usize)> {
429
430 // Could be \o, \oo, or \ooo
431 let str = iter.as_str();
432 let end = iter.clone() // Cloning this is pretty cheap
433 .take(2)
434 .take_while(|(_, c)| c.is_digit(8))
435 .enumerate()
436 .last()
437 .map_or(0, |(idx, _)| idx + 1);
438 let num = &str[ .. end];
439 // These are the characters _after_ the first
440 let mut codepoint = if num.is_empty() { 0 } else { u32::from_str_radix(num, 8).ok()? };
441 // Add the first character at the top of the number
442 codepoint += (chr as u32 - '0' as u32) * 8u32.pow(end as u32);
443 char::from_u32(codepoint).map(|chr| (chr, end))
444 }
445