1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use crate::{Bytes, BytesMut, BytesVec};
use std::fmt::{Formatter, LowerHex, Result, UpperHex};

struct BytesRef<'a>(&'a [u8]);

impl<'a> LowerHex for BytesRef<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        for b in self.0 {
            write!(f, "{b:02x}")?;
        }
        Ok(())
    }
}

impl<'a> UpperHex for BytesRef<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        for b in self.0 {
            write!(f, "{b:02X}")?;
        }
        Ok(())
    }
}

macro_rules! hex_impl {
    ($tr:ident, $ty:ty) => {
        impl $tr for $ty {
            fn fmt(&self, f: &mut Formatter<'_>) -> Result {
                $tr::fmt(&BytesRef(self.as_ref()), f)
            }
        }
    };
}

hex_impl!(LowerHex, Bytes);
hex_impl!(LowerHex, BytesMut);
hex_impl!(LowerHex, BytesVec);
hex_impl!(UpperHex, Bytes);
hex_impl!(UpperHex, BytesMut);
hex_impl!(UpperHex, BytesVec);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hex() {
        let b = Bytes::from_static(b"hello world");
        let f = format!("{:x}", b);
        assert_eq!(f, "68656c6c6f20776f726c64");
        let f = format!("{:X}", b);
        assert_eq!(f, "68656C6C6F20776F726C64");
    }
}