File tree Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -82,9 +82,40 @@ impl TryFrom<Data> for String {
8282impl fmt:: Display for Data {
8383 fn fmt ( & self , f : & mut Formatter < ' _ > ) -> fmt:: Result {
8484 match self {
85- Data :: Binary ( vec) => write ! ( f, "Binary data: {:?}" , str :: from_utf8( vec) . unwrap( ) ) ,
85+ Data :: Binary ( vec) => {
86+ write ! ( f, "Binary data: " ) ?;
87+ let mut slice = & vec[ ..] ;
88+ loop {
89+ match str:: from_utf8 ( slice) {
90+ Ok ( s) => break f. write_str ( s) ,
91+ Err ( e) => {
92+ let ( good, bad) = slice. split_at ( e. valid_up_to ( ) ) ;
93+
94+ // SAFETY: good is a valid utf8 sequency because
95+ f. write_str ( unsafe { str:: from_utf8_unchecked ( good) } ) ?;
96+
97+ write ! ( f, "\\ x{:02X}" , bad[ 0 ] ) ?;
98+ slice = & bad[ 1 ..] ;
99+ }
100+ }
101+ }
102+ }
86103 Data :: String ( s) => write ! ( f, "String data: {}" , s) ,
87104 Data :: Json ( j) => write ! ( f, "Json data: {}" , j) ,
88105 }
89106 }
90107}
108+
109+ #[ cfg( test) ]
110+ mod tests {
111+ use crate :: Data ;
112+
113+ #[ test]
114+ fn display_arbitrary_bytes ( ) {
115+ let d = Data :: Binary ( b"E onde sou s\xC3 \xB3 desejo, queres n\xC3 \xA3 o\xF0 \x90 " . into ( ) ) ;
116+ assert_eq ! (
117+ format!( "{}" , d) ,
118+ r"Binary data: E onde sou só desejo, queres não\xF0\x90"
119+ ) ;
120+ }
121+ }
You can’t perform that action at this time.
0 commit comments