1use std::fmt::{Formatter, LowerHex, Result, UpperHex};
2
3use crate::{Bytes, BytesMut, BytesVec};
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!(LowerHex, BytesVec);
38hex_impl!(UpperHex, Bytes);
39hex_impl!(UpperHex, BytesMut);
40hex_impl!(UpperHex, BytesVec);
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn hex() {
48 let b = Bytes::from_static(b"hello world");
49 let f = format!("{b:x}");
50 assert_eq!(f, "68656c6c6f20776f726c64");
51 let f = format!("{b:X}");
52 assert_eq!(f, "68656C6C6F20776F726C64");
53 }
54}