File tree Expand file tree Collapse file tree 1 file changed +30
-1
lines changed Expand file tree Collapse file tree 1 file changed +30
-1
lines changed Original file line number Diff line number Diff line change @@ -82,9 +82,38 @@ 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+ f. write_str ( str:: from_utf8 ( good) . unwrap ( ) ) ?;
95+ write ! ( f, "\\ x{:02X}" , bad[ 0 ] ) ?;
96+ slice = & bad[ 1 ..] ;
97+ }
98+ }
99+ }
100+ }
86101 Data :: String ( s) => write ! ( f, "String data: {}" , s) ,
87102 Data :: Json ( j) => write ! ( f, "Json data: {}" , j) ,
88103 }
89104 }
90105}
106+
107+ #[ cfg( test) ]
108+ mod tests {
109+ use crate :: Data ;
110+
111+ #[ test]
112+ fn display_arbitrary_bytes ( ) {
113+ let d = Data :: Binary ( b"E onde sou s\xC3 \xB3 desejo, queres n\xC3 \xA3 o\xF0 \x90 " . into ( ) ) ;
114+ assert_eq ! (
115+ format!( "{}" , d) ,
116+ r"Binary data: E onde sou só desejo, queres não\xF0\x90"
117+ ) ;
118+ }
119+ }
You can’t perform that action at this time.
0 commit comments