osom_lib_test_macros/models/
display_as_hex.rs

1use core::fmt;
2
3/// A simple wrapper around a slice of bytes that implements `Display`
4/// which display the slice in the form of hex bytes.
5#[must_use]
6#[repr(transparent)]
7pub struct DisplayAsHex<'a> {
8    data: &'a [u8],
9}
10
11impl<'a> DisplayAsHex<'a> {
12    #[inline(always)]
13    pub const fn new(data: &'a [u8]) -> Self {
14        Self { data }
15    }
16
17    #[inline(always)]
18    #[must_use]
19    pub fn as_slice(&self) -> &[u8] {
20        self.data
21    }
22}
23
24impl fmt::Display for DisplayAsHex<'_> {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "[")?;
27
28        let mut iter = self.data.iter();
29        if let Some(byte) = iter.next() {
30            write!(f, "{byte:#04x}")?;
31            for byte in iter {
32                write!(f, ", {byte:#04x}")?;
33            }
34        }
35
36        write!(f, "]")
37    }
38}