You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
videl/src/ext.rs

63 lines
899 B

//! Extensions
use std::{
fmt::{
Write as _,
},
};
pub struct HexSlice<'a>(&'a [u8]);
impl<'a> HexSlice<'a>
{
#[inline] pub fn new<T>(from: &'a T) -> Self
where T: AsRef<[u8]> + ?Sized + 'a
{
Self(from.as_ref())
}
pub fn to_hex_string(&self) -> String
{
let mut output = String::with_capacity(self.0.len()*2);
write!(output, "{}", self).unwrap();
output
}
}
impl std::fmt::Display for HexSlice<'_>
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
{
for byte in self.0.iter()
{
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
pub trait HexSliceExt
{
fn as_hex(&self) -> HexSlice<'_>;
}
impl<T> HexSliceExt for T
where T: AsRef<[u8]>
{
#[inline] fn as_hex(&self) -> HexSlice<'_>
{
HexSlice(self.as_ref())
}
}
impl AsRef<[u8]> for HexSlice<'_>
{
fn as_ref(&self) -> &[u8]
{
self.0
}
}