Debian Codegraph @

src/shared/util/escape.rs

raw symbols SCIP
1 // auto-generated by: jiff-cli generate shared
2
3 /*!
4 Provides convenience routines for escaping raw bytes.
5
6 This was copied from `regex-automata` with a few light edits.
7 */
8
9 use super::utf8;
10
11 /// Provides a convenient `Debug` implementation for a `u8`.
12 ///
13 /// The `Debug` impl treats the byte as an ASCII, and emits a human
14 /// readable representation of it. If the byte isn't ASCII, then it's
15 /// emitted as a hex escape sequence.
16 #[derive(Clone, Copy)]
17 pub(crate) struct Byte(pub u8);
18
19 impl core::fmt::Display for Byte {
20 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
21 if self.0 == b' ' {
22 return write!(f, " ");
23 }
24 // 10 bytes is enough for any output from ascii::escape_default.
25 let mut bytes = [0u8; 10];
26 let mut len = 0;
27 for (i, mut b) in core::ascii::escape_default(self.0).enumerate() {
28 // capitalize \xab to \xAB
29 if i >= 2 && b'a' <= b && b <= b'f' {
30 b -= 32;
31 }
32 bytes[len] = b;
33 len += 1;
34 }
35 write!(f, "{}", core::str::from_utf8(&bytes[..len]).unwrap())
36 }
37 }
38
39 impl core::fmt::Debug for Byte {
40 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
41 write!(f, "\"")?;
42 core::fmt::Display::fmt(self, f)?;
43 write!(f, "\"")?;
44 Ok(())
45 }
46 }
47
48 /// Provides a convenient `Debug` implementation for `&[u8]`.
49 ///
50 /// This generally works best when the bytes are presumed to be mostly
51 /// UTF-8, but will work for anything. For any bytes that aren't UTF-8,
52 /// they are emitted as hex escape sequences.
53 #[derive(Clone, Copy)]
54 pub(crate) struct Bytes<'a>(pub &'a [u8]);
55
56 impl<'a> core::fmt::Display for Bytes<'a> {
57 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
58 // This is a sad re-implementation of a similar impl found in bstr.
59 let mut bytes = self.0;
60 while let Some(result) = utf8::decode(bytes) {
61 let ch = match result {
62 Ok(ch) => ch,
63 Err(errant_bytes) => {
64 // The decode API guarantees `errant_bytes` is non-empty.
65 write!(f, r"\x{:02x}", errant_bytes[0])?;
66 bytes = &bytes[1..];
67 continue;
68 }
69 };
70 bytes = &bytes[ch.len_utf8()..];
71 match ch {
72 '\0' => write!(f, "\\0")?,
73 '\x01'..='\x7f' => {
74 write!(f, "{}", (ch as u8).escape_ascii())?;
75 }
76 _ => write!(f, "{}", ch.escape_debug())?,
77 }
78 }
79 Ok(())
80 }
81 }
82
83 impl<'a> core::fmt::Debug for Bytes<'a> {
84 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
85 write!(f, "\"")?;
86 core::fmt::Display::fmt(self, f)?;
87 write!(f, "\"")?;
88 Ok(())
89 }
90 }