musli_zerocopy/
lossy_str.rs1use core::fmt;
2use core::str;
3
4#[repr(transparent)]
5pub(crate) struct LossyStr([u8]);
6
7impl LossyStr {
8 pub(crate) fn new<S>(bytes: &S) -> &Self
10 where
11 S: ?Sized + AsRef<[u8]>,
12 {
13 unsafe { &*(bytes.as_ref() as *const [u8] as *const LossyStr) }
15 }
16}
17
18impl fmt::Debug for LossyStr {
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 let mut bytes = &self.0;
21
22 write!(f, "\"")?;
23
24 loop {
25 let (string, replacement) = match str::from_utf8(bytes) {
26 Ok(s) => (s, false),
27 Err(e) => {
28 let (valid, invalid) = bytes.split_at(e.valid_up_to());
29 bytes = invalid.get(1..).unwrap_or_default();
30 (unsafe { str::from_utf8_unchecked(valid) }, true)
31 }
32 };
33
34 for c in string.chars() {
35 match c {
36 '\0' => write!(f, "\\0")?,
37 '\x01'..='\x08' | '\x0b' | '\x0c' | '\x0e'..='\x19' | '\x7f' => {
38 write!(f, "\\x{:02x}", c as u32)?;
39 }
40 _ => {
41 write!(f, "{}", c.escape_debug())?;
42 }
43 }
44 }
45
46 if !replacement {
47 break;
48 }
49
50 write!(f, "\u{FFFD}")?;
51 }
52
53 write!(f, "\"")?;
54 Ok(())
55 }
56}