1use core::fmt::{Debug, Formatter, Result};
23use super::BytesRef;
4use crate::{Bytes, BytesMut};
56/// Alternative implementation of `std::fmt::Debug` for byte slice.
7///
8/// Standard `Debug` implementation for `[u8]` is comma separated
9/// list of numbers. Since large amount of byte strings are in fact
10/// ASCII strings or contain a lot of ASCII strings (e. g. HTTP),
11/// it is convenient to print strings as ASCII when possible.
12impl Debug for BytesRef<'_> {
13fn fmt(&self, f: &mut Formatter<'_>) -> Result {
14write!(f, "b\"")?;
15for &b in self.0 {
16// https://doc.rust-lang.org/reference/tokens.html#byte-escapes
17if b == b'\n' {
18write!(f, "\\n")?;
19 } else if b == b'\r' {
20write!(f, "\\r")?;
21 } else if b == b'\t' {
22write!(f, "\\t")?;
23 } else if b == b'\\' || b == b'"' {
24write!(f, "\\{}", b as char)?;
25 } else if b == b'\0' {
26write!(f, "\\0")?;
27// ASCII printable
28} else if (0x20..0x7f).contains(&b) {
29write!(f, "{}", b as char)?;
30 } else {
31write!(f, "\\x{:02x}", b)?;
32 }
33 }
34write!(f, "\"")?;
35Ok(())
36 }
37}
3839fmt_impl!(Debug, Bytes);
40fmt_impl!(Debug, BytesMut);