use std::fmt;
use std::str::FromStr;
use hex_conservative::{
fmt_hex_exact, Case, DisplayHex, FromHex, HexToArrayError, HexToBytesError,
};
fn main() {
let s = "deadbeefcafebabedeadbeefcafebabedeadbeefcafebabedeadbeefcafebabe";
println!("Parse hex from string: {}", s);
let hexy = Hexy::from_hex(s).expect("the correct number of valid hex digits");
let display = format!("{}", hexy);
println!("Display Hexy as string: {}", display);
assert_eq!(display, s);
}
pub struct Hexy {
data: [u8; 32],
}
impl Hexy {
pub fn as_bytes(&self) -> &[u8] { &self.data }
}
impl fmt::Debug for Hexy {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
fmt::Formatter::debug_struct(f, "Hexy").field("data", &self.data.as_hex()).finish()
}
}
impl fmt::Display for Hexy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
}
impl FromStr for Hexy {
type Err = HexToArrayError;
fn from_str(s: &str) -> Result<Self, Self::Err> { Hexy::from_hex(s) }
}
impl fmt::LowerHex for Hexy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_hex_exact!(f, 32, self.as_bytes(), Case::Lower)
}
}
impl fmt::UpperHex for Hexy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_hex_exact!(f, 32, self.as_bytes(), Case::Upper)
}
}
impl FromHex for Hexy {
type Err = HexToArrayError;
fn from_byte_iter<I>(iter: I) -> Result<Self, Self::Err>
where
I: Iterator<Item = Result<u8, HexToBytesError>> + ExactSizeIterator + DoubleEndedIterator,
{
let a = <[u8; 32] as FromHex>::from_byte_iter(iter)?;
Ok(Hexy { data: a })
}
}