From 9cddc903a65d027f3c739479c9f262993b22f902 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 | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/impls.rs b/src/impls.rs index 375e5be..d7c08c2 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -329,12 +329,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, "\"")?; @@ -759,3 +771,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()), + ); +}