use alloc::string::String;
use core::fmt;
pub trait ToHex {
fn to_hex(&self) -> String;
fn to_hex_with_prefix(&self) -> String;
}
impl ToHex for [u8] {
fn to_hex(&self) -> String {
format!("{:x}", DisplayHex(self))
}
fn to_hex_with_prefix(&self) -> String {
format!("{:#x}", DisplayHex(self))
}
}
impl<'a> ToHex for DisplayHex<'a> {
fn to_hex(&self) -> String {
format!("{:x}", self)
}
fn to_hex_with_prefix(&self) -> String {
format!("{:#x}", self)
}
}
#[inline]
pub fn to_hex(bytes: impl AsRef<[u8]>) -> String {
bytes.as_ref().to_hex()
}
pub struct DisplayHex<'a>(pub &'a [u8]);
impl<'a> DisplayHex<'a> {
#[inline]
pub fn new<'b: 'a, T>(item: &'b T) -> Self
where
T: AsRef<[u8]>,
{
Self(item.as_ref())
}
}
impl<'a> fmt::Display for DisplayHex<'a> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl<'a> fmt::LowerHex for DisplayHex<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
f.write_str("0x")?;
}
for byte in self.0.iter() {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl<'a> crate::prettier::PrettyPrint for DisplayHex<'a> {
fn render(&self) -> crate::prettier::Document {
crate::prettier::text(format!("{:#x}", self))
}
}