]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/bytestring.rs
Auto merge of #68522 - estebank:impl-trait-sugg-2, r=oli-obk
[rust.git] / src / libstd / sys_common / bytestring.rs
1 #![allow(dead_code)]
2
3 use crate::fmt::{Formatter, Result, Write};
4 use core::str::lossy::{Utf8Lossy, Utf8LossyChunk};
5
6 pub fn debug_fmt_bytestring(slice: &[u8], f: &mut Formatter<'_>) -> Result {
7     // Writes out a valid unicode string with the correct escape sequences
8     fn write_str_escaped(f: &mut Formatter<'_>, s: &str) -> Result {
9         for c in s.chars().flat_map(|c| c.escape_debug()) {
10             f.write_char(c)?
11         }
12         Ok(())
13     }
14
15     f.write_str("\"")?;
16     for Utf8LossyChunk { valid, broken } in Utf8Lossy::from_bytes(slice).chunks() {
17         write_str_escaped(f, valid)?;
18         for b in broken {
19             write!(f, "\\x{:02X}", b)?;
20         }
21     }
22     f.write_str("\"")
23 }
24
25 #[cfg(test)]
26 mod tests {
27     use super::*;
28     use crate::fmt::{Debug, Formatter, Result};
29
30     #[test]
31     fn smoke() {
32         struct Helper<'a>(&'a [u8]);
33
34         impl Debug for Helper<'_> {
35             fn fmt(&self, f: &mut Formatter<'_>) -> Result {
36                 debug_fmt_bytestring(self.0, f)
37             }
38         }
39
40         let input = b"\xF0hello,\tworld";
41         let expected = r#""\xF0hello,\tworld""#;
42         let output = format!("{:?}", Helper(input));
43
44         assert!(output == expected);
45     }
46 }