Skip to main content

dezoomify_rs/
binary_display.rs

1use std::fmt;
2
3/// A wrapper struct to display binary data in a Python-like format
4///
5/// This displays binary data as b'...' with printable ASCII characters shown as-is
6/// and non-printable characters shown as escape sequences like \x00, \x01, etc.
7pub struct BinaryDisplay<'a>(pub &'a [u8]);
8
9impl fmt::Display for BinaryDisplay<'_> {
10    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11        write!(f, "b'")?;
12
13        for &byte in self.0 {
14            match byte {
15                // Printable ASCII characters (space to tilde)
16                0x20..=0x7e => write!(f, "{}", byte as char)?,
17                // Non-printable characters as hex escape sequences
18                _ => write!(f, "\\x{byte:02x}")?,
19            }
20        }
21
22        write!(f, "'")
23    }
24}
25
26impl fmt::Debug for BinaryDisplay<'_> {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        fmt::Display::fmt(self, f)
29    }
30}
31
32/// Convenience function to create a `BinaryDisplay` wrapper
33pub fn display_bytes<T: AsRef<[u8]> + ?Sized>(bytes: &T) -> BinaryDisplay<'_> {
34    BinaryDisplay(bytes.as_ref())
35}