xsd_parser/models/
raw_byte_str.rs

1use std::borrow::Cow;
2use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
3
4/// Helper type that implements [`Debug`] and [`Display`] for a byte slice.
5pub struct RawByteStr(Cow<'static, [u8]>);
6
7impl RawByteStr {
8    /// Create a new [`RawByteStr`] instance from the passed byte slice.
9    #[must_use]
10    pub fn from_slice(value: &[u8]) -> Self {
11        Self(Cow::Owned(value.to_owned()))
12    }
13}
14
15impl From<Vec<u8>> for RawByteStr {
16    fn from(value: Vec<u8>) -> Self {
17        Self(Cow::Owned(value))
18    }
19}
20
21impl From<&'static [u8]> for RawByteStr {
22    fn from(value: &'static [u8]) -> Self {
23        Self(Cow::Borrowed(value))
24    }
25}
26
27impl From<&'static str> for RawByteStr {
28    fn from(value: &'static str) -> Self {
29        Self(Cow::Borrowed(value.as_bytes()))
30    }
31}
32
33impl Debug for RawByteStr {
34    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
35        write!(f, "\"")?;
36        format_utf8_slice(&self.0, f)?;
37        write!(f, "\"")?;
38
39        Ok(())
40    }
41}
42
43impl Display for RawByteStr {
44    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
45        write!(f, "\"")?;
46        format_utf8_slice(&self.0, f)?;
47        write!(f, "\"")?;
48
49        Ok(())
50    }
51}
52
53pub(crate) fn format_utf8_slice(bytes: &[u8], f: &mut Formatter<'_>) -> FmtResult {
54    for byte in bytes {
55        if byte.is_ascii_control() {
56            write!(f, r"\x{byte:02X}")?;
57        } else {
58            write!(f, "{}", *byte as char)?;
59        }
60    }
61
62    Ok(())
63}