cnidarium/
escaped_byte_slice.rs

1/// A wrapper type for a byte slice that implements `Debug` by escaping
2/// non-printable bytes.
3///
4/// This is exposed as part of the public API for convenience of downstream
5/// users' debugging of state accesses.
6pub struct EscapedByteSlice<'a>(pub &'a [u8]);
7
8impl<'a> std::fmt::Debug for EscapedByteSlice<'a> {
9    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10        write!(f, "b\"")?;
11        for &b in self.0 {
12            // https://doc.rust-lang.org/reference/tokens.html#byte-escapes
13            #[allow(clippy::manual_range_contains)]
14            if b == b'\n' {
15                write!(f, "\\n")?;
16            } else if b == b'\r' {
17                write!(f, "\\r")?;
18            } else if b == b'\t' {
19                write!(f, "\\t")?;
20            } else if b == b'\\' || b == b'"' {
21                write!(f, "\\{}", b as char)?;
22            } else if b == b'\0' {
23                write!(f, "\\0")?;
24            // ASCII printable
25            } else if b >= 0x20 && b < 0x7f {
26                write!(f, "{}", b as char)?;
27            } else {
28                write!(f, "\\x{:02x}", b)?;
29            }
30        }
31        write!(f, "\"")?;
32        Ok(())
33    }
34}