Display potentially non-UTF8 string in a lossy way, *without* allocating a new buffer to hold the string.
(input: &[u8])
| 6 | /// Display potentially non-UTF8 string in a lossy way, *without* allocating a new buffer to hold |
| 7 | /// the string. |
| 8 | pub fn display_utf8_lossy(input: &[u8]) -> impl fmt::Display + '_ { |
| 9 | struct StringDisplay<'a>(&'a [u8]); |
| 10 | |
| 11 | impl fmt::Display for StringDisplay<'_> { |
| 12 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 13 | let mut input = self.0; |
| 14 | loop { |
| 15 | match str::from_utf8(input) { |
| 16 | Ok(valid) => { |
| 17 | f.write_str(valid)?; |
| 18 | break; |
| 19 | } |
| 20 | Err(error) => { |
| 21 | let (valid, after_valid) = input.split_at(error.valid_up_to()); |
| 22 | f.write_str(str::from_utf8(valid).unwrap())?; |
| 23 | f.write_str("\u{FFFD}")?; |
| 24 | |
| 25 | if let Some(invalid_sequence_length) = error.error_len() { |
| 26 | input = &after_valid[invalid_sequence_length..] |
| 27 | } else { |
| 28 | break; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | Ok(()) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | StringDisplay(input) |
| 38 | } |
| 39 | |
| 40 | /// Like [`display_utf8_lossy`], returns an `impl fmt::Debug` type that uses debug character escapes |
| 41 | /// and surrounds the string by '"' characters. |
no test coverage detected