ntex_bytes/debug.rs
1use std::fmt;
2
3/// Alternative implementation of `fmt::Debug` for byte slice.
4///
5/// Standard `Debug` implementation for `[u8]` is comma separated
6/// list of numbers. Since large amount of byte strings are in fact
7/// ASCII strings or contain a lot of ASCII strings (e. g. HTTP),
8/// it is convenient to print strings as ASCII when possible.
9///
10/// This struct wraps `&[u8]` just to override `fmt::Debug`.
11///
12/// `BsDebug` is not a part of public API of bytes crate.
13pub struct BsDebug<'a>(pub &'a [u8]);
14
15impl fmt::Debug for BsDebug<'_> {
16 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
17 write!(fmt, "b\"")?;
18 for &c in self.0 {
19 // https://doc.rust-lang.org/reference.html#byte-escapes
20 if c == b'\n' {
21 write!(fmt, "\\n")?;
22 } else if c == b'\r' {
23 write!(fmt, "\\r")?;
24 } else if c == b'\t' {
25 write!(fmt, "\\t")?;
26 } else if c == b'\\' || c == b'"' {
27 write!(fmt, "\\{}", c as char)?;
28 } else if c == b'\0' {
29 write!(fmt, "\\0")?;
30 // ASCII printable
31 } else if (0x20..0x7f).contains(&c) {
32 write!(fmt, "{}", c as char)?;
33 } else {
34 write!(fmt, "\\x{c:02x}")?;
35 }
36 }
37 write!(fmt, "\"")?;
38 Ok(())
39 }
40}