use std::fmt;
use std::str::FromStr;
use hex_conservative::{
self as hex, fmt_hex_exact, Case, DecodeFixedLengthBytesError, DisplayHex as _,
};
fn main() {
let s = "deadbeefcafebabedeadbeefcafebabedeadbeefcafebabedeadbeefcafebabe";
println!("Parse hex from string: {}", s);
let hexy = s.parse::<Hexy>().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 = DecodeFixedLengthBytesError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let a = hex::decode_to_array::<32>(s)?;
Ok(Hexy { data: a })
}
}
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)
}
}