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