@@ -426,26 +426,36 @@ impl Ord for Wtf8 {
426
426
/// and surrogates as `\u` followed by four hexadecimal digits.
427
427
/// Example: `"a\u{D800}"` for a slice with code points [U+0061, U+D800]
428
428
impl fmt:: Debug for Wtf8 {
429
- fn fmt ( & self , formatter : & mut fmt:: Formatter ) -> Result < ( ) , fmt:: Error > {
429
+ fn fmt ( & self , formatter : & mut fmt:: Formatter ) -> fmt:: Result {
430
+ fn write_str_escaped ( f : & mut fmt:: Formatter , s : & str ) -> fmt:: Result {
431
+ use fmt:: Write ;
432
+ for c in s. chars ( ) . flat_map ( |c| c. escape_default ( ) ) {
433
+ try!( f. write_char ( c) )
434
+ }
435
+ Ok ( ( ) )
436
+ }
437
+
430
438
try!( formatter. write_str ( "\" " ) ) ;
431
439
let mut pos = 0 ;
432
440
loop {
433
441
match self . next_surrogate ( pos) {
434
442
None => break ,
435
443
Some ( ( surrogate_pos, surrogate) ) => {
436
- try!( formatter. write_str ( unsafe {
437
- // the data in this slice is valid UTF-8, transmute to &str
438
- mem:: transmute ( & self . bytes [ pos .. surrogate_pos] )
439
- } ) ) ;
444
+ try!( write_str_escaped (
445
+ formatter,
446
+ unsafe { str:: from_utf8_unchecked (
447
+ & self . bytes [ pos .. surrogate_pos]
448
+ ) } ,
449
+ ) ) ;
440
450
try!( write ! ( formatter, "\\ u{{{:X}}}" , surrogate) ) ;
441
451
pos = surrogate_pos + 3 ;
442
452
}
443
453
}
444
454
}
445
- try!( formatter . write_str ( unsafe {
446
- // the data in this slice is valid UTF-8, transmute to &str
447
- mem :: transmute ( & self . bytes [ pos..] )
448
- } ) ) ;
455
+ try!( write_str_escaped (
456
+ formatter ,
457
+ unsafe { str :: from_utf8_unchecked ( & self . bytes [ pos..] ) } ,
458
+ ) ) ;
449
459
formatter. write_str ( "\" " )
450
460
}
451
461
}
@@ -1083,9 +1093,9 @@ mod tests {
1083
1093
1084
1094
#[ test]
1085
1095
fn wtf8buf_show ( ) {
1086
- let mut string = Wtf8Buf :: from_str ( "aé 💩 " ) ;
1096
+ let mut string = Wtf8Buf :: from_str ( "a \t é 💩 \r " ) ;
1087
1097
string. push ( CodePoint :: from_u32 ( 0xD800 ) . unwrap ( ) ) ;
1088
- assert_eq ! ( format!( "{:?}" , string) , r#""aé 💩 \u{D800}""# ) ;
1098
+ assert_eq ! ( format!( "{:?}" , string) , r#""a\t\u{e9} \u{1f4a9}\r \u{D800}""# ) ;
1089
1099
}
1090
1100
1091
1101
#[ test]
@@ -1094,10 +1104,10 @@ mod tests {
1094
1104
}
1095
1105
1096
1106
#[ test]
1097
- fn wtf8_show ( ) {
1098
- let mut string = Wtf8Buf :: from_str ( "aé 💩" ) ;
1099
- string. push ( CodePoint :: from_u32 ( 0xD800 ) . unwrap ( ) ) ;
1100
- assert_eq ! ( format!( "{:?}" , string ) , r#""aé 💩\u{D800}""# ) ;
1107
+ fn wtf8buf_show_str ( ) {
1108
+ let text = "a \t é 💩 \r " ;
1109
+ let mut string = Wtf8Buf :: from_str ( text ) ;
1110
+ assert_eq ! ( format!( "{:?}" , text ) , format! ( "{:?}" , string ) ) ;
1101
1111
}
1102
1112
1103
1113
#[ test]
0 commit comments