1use alloc::string::String;
4use core::fmt;
5
6pub trait ToHex {
13 fn to_hex(&self) -> String;
19 fn to_hex_with_prefix(&self) -> String;
21}
22
23impl ToHex for [u8] {
24 fn to_hex(&self) -> String {
25 format!("{:x}", DisplayHex(self))
26 }
27
28 fn to_hex_with_prefix(&self) -> String {
29 format!("{:#x}", DisplayHex(self))
30 }
31}
32
33impl<'a> ToHex for DisplayHex<'a> {
34 fn to_hex(&self) -> String {
35 format!("{:x}", self)
36 }
37
38 fn to_hex_with_prefix(&self) -> String {
39 format!("{:#x}", self)
40 }
41}
42
43#[inline]
45pub fn to_hex(bytes: impl AsRef<[u8]>) -> String {
46 bytes.as_ref().to_hex()
47}
48
49pub struct DisplayHex<'a>(pub &'a [u8]);
52
53impl<'a> DisplayHex<'a> {
54 #[inline]
56 pub fn new<'b: 'a, T>(item: &'b T) -> Self
57 where
58 T: AsRef<[u8]>,
59 {
60 Self(item.as_ref())
61 }
62}
63
64impl<'a> fmt::Display for DisplayHex<'a> {
65 #[inline]
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67 fmt::LowerHex::fmt(self, f)
68 }
69}
70
71impl<'a> fmt::LowerHex for DisplayHex<'a> {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 if f.alternate() {
74 f.write_str("0x")?;
75 }
76 for byte in self.0.iter() {
77 write!(f, "{byte:02x}")?;
78 }
79 Ok(())
80 }
81}
82
83impl<'a> crate::prettier::PrettyPrint for DisplayHex<'a> {
84 fn render(&self) -> crate::prettier::Document {
85 crate::prettier::text(format!("{:#x}", self))
86 }
87}