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 #[test]
45 fn hex() {
46 let b = Bytes::from_static(b"hello world");
47 let f = format!("{b:x}");
48 assert_eq!(f, "68656c6c6f20776f726c64");
49 let f = format!("{b:X}");
50 assert_eq!(f, "68656C6C6F20776F726C64");
51 }
52}