Debian Codegraph @

third_party/rust/unix_str/src/sys_common/bytestring.rs

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