Skip to content

Commit

Permalink
impl: improve Debug impl for BStr
Browse files Browse the repository at this point in the history
Previously, any non-printable Unicode scalar value would get printed
using the '\u{...}' syntax. While not horrible, it's a bit weird to
do this for ASCII characters and especially for the NUL and various
whitespace characters. So this commit tweaks the Debug impl for BStr to
handle those cases specially in a way that's a bit more consistent with
what folks expect.

Fixes #56, Closes #58
  • Loading branch information
tailhook authored and BurntSushi committed Oct 18, 2020
1 parent 282ff2b commit fdf9860
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,12 +375,24 @@ mod bstr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\"")?;
for (s, e, ch) in self.char_indices() {
if ch == '\u{FFFD}' {
for &b in self[s..e].as_bytes() {
write!(f, r"\x{:X}", b)?;
match ch {
'\0' => write!(f, "\\0")?,
'\u{FFFD}' => {
for &b in self[s..e].as_bytes() {
write!(f, r"\x{:02X}", b)?;
}
}
// ASCII control characters except \0, \n, \r, \t
'\x01'..='\x08'
| '\x0b'
| '\x0c'
| '\x0e'..='\x19'
| '\x7f' => {
write!(f, "\\x{:02x}", ch as u32)?;
}
'\n' | '\r' | '\t' | _ => {
write!(f, "{}", ch.escape_debug())?;
}
} else {
write!(f, "{}", ch.escape_debug())?;
}
}
write!(f, "\"")?;
Expand Down Expand Up @@ -930,3 +942,12 @@ mod bstring_arbitrary {
}
}
}

#[test]
fn test_debug() {
use crate::ByteSlice;
assert_eq!(
r#""\0\0\0 ftypisom\0\0\x02\0isomiso2avc1mp""#,
format!("{:?}", b"\0\0\0 ftypisom\0\0\x02\0isomiso2avc1mp".as_bstr()),
);
}

0 comments on commit fdf9860

Please sign in to comment.