fixed_buffer/
escape_ascii.rs

1/// Convert a byte slice into a string.
2/// Includes printable ASCII characters as-is.
3/// Converts non-printable or non-ASCII characters to strings like "\n" and "\x19".
4///
5/// Uses
6/// [`core::ascii::escape_default`](https://doc.rust-lang.org/core/ascii/fn.escape_default.html)
7/// internally to escape each byte.
8///
9/// This function is useful for printing byte slices to logs and comparing byte slices in tests.
10///
11/// Example test:
12/// ```
13/// use fixed_buffer::escape_ascii;
14/// assert_eq!("abc", escape_ascii(b"abc"));
15/// assert_eq!("abc\\n", escape_ascii(b"abc\n"));
16/// assert_eq!(
17///     "Euro sign: \\xe2\\x82\\xac",
18///     escape_ascii("Euro sign: \u{20AC}".as_bytes())
19/// );
20/// assert_eq!("\\x01\\x02\\x03", escape_ascii(&[1, 2, 3]));
21/// ```
22#[must_use]
23#[allow(clippy::missing_panics_doc)]
24pub fn escape_ascii(input: &[u8]) -> String {
25    let mut result = String::new();
26    for byte in input {
27        for ascii_byte in core::ascii::escape_default(*byte) {
28            result.push_str(core::str::from_utf8(&[ascii_byte]).unwrap());
29        }
30    }
31    result
32}