Skip to main content

ntex_bytes/
hex.rs

1use std::fmt::{Formatter, LowerHex, Result, UpperHex};
2
3use crate::{Bytes, BytesMut};
4
5struct BytesRef<'a>(&'a [u8]);
6
7impl LowerHex for BytesRef<'_> {
8    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
9        for b in self.0 {
10            write!(f, "{b:02x}")?;
11        }
12        Ok(())
13    }
14}
15
16impl UpperHex for BytesRef<'_> {
17    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
18        for b in self.0 {
19            write!(f, "{b:02X}")?;
20        }
21        Ok(())
22    }
23}
24
25macro_rules! hex_impl {
26    ($tr:ident, $ty:ty) => {
27        impl $tr for $ty {
28            fn fmt(&self, f: &mut Formatter<'_>) -> Result {
29                $tr::fmt(&BytesRef(self.as_ref()), f)
30            }
31        }
32    };
33}
34
35hex_impl!(LowerHex, Bytes);
36hex_impl!(LowerHex, BytesMut);
37hex_impl!(UpperHex, Bytes);
38hex_impl!(UpperHex, BytesMut);
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    /// STATEMENT: Hex formatting respects lowercase and uppercase digits for `Bytes`.
45    ///
46    /// HOW:
47    /// - Format static `hello world` with `x` and `X` and compare both complete hexadecimal strings.
48    #[test]
49    fn hex() {
50        let b = Bytes::from_static(b"hello world");
51        let f = format!("{b:x}");
52        assert_eq!(f, "68656c6c6f20776f726c64");
53        let f = format!("{b:X}");
54        assert_eq!(f, "68656C6C6F20776F726C64");
55    }
56}