From cd1db3bdc42dc40178950d64c84501ff19a59dad Mon Sep 17 00:00:00 2001 From: Paul Colomiets Date: Thu, 11 Jun 2020 16:33:05 +0300 Subject: [PATCH] Better (shorter, clearer) debug implementation Fixes #56 --- src/impls.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/impls.rs b/src/impls.rs index 375e5be..a60e1ea 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -329,13 +329,22 @@ 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)?; + } } - } else { - write!(f, "{}", ch.escape_debug())?; - } + // 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())?; + } + } } write!(f, "\"")?; Ok(()) @@ -759,3 +768,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())); +} +