1use std::fmt;
9use std::str::FromStr;
10
11use hex_conservative::{
12 self as hex, fmt_hex_exact, Case, DecodeFixedLengthBytesError, DisplayHex as _,
13};
14
15fn main() {
16 let s = "deadbeefcafebabedeadbeefcafebabedeadbeefcafebabedeadbeefcafebabe";
17 println!("Parse hex from string: {}", s);
18
19 let hexy = s.parse::<Hexy>().expect("the correct number of valid hex digits");
20 let display = format!("{}", hexy);
21 println!("Display Hexy as string: {}", display);
22
23 assert_eq!(display, s);
24}
25
26pub struct Hexy {
28 data: [u8; 32],
30}
31
32impl Hexy {
33 pub fn as_bytes(&self) -> &[u8] { &self.data }
35}
36
37impl fmt::Debug for Hexy {
38 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
39 fmt::Formatter::debug_struct(f, "Hexy").field("data", &self.data.as_hex()).finish()
40 }
41}
42
43impl fmt::Display for Hexy {
47 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
48}
49
50impl FromStr for Hexy {
51 type Err = DecodeFixedLengthBytesError;
52
53 fn from_str(s: &str) -> Result<Self, Self::Err> {
54 let a = hex::decode_to_array::<32>(s)?;
56 Ok(Hexy { data: a })
57 }
58}
59
60impl fmt::LowerHex for Hexy {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 fmt_hex_exact!(f, 32, self.as_bytes(), Case::Lower)
67 }
68}
69
70impl fmt::UpperHex for Hexy {
71 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72 fmt_hex_exact!(f, 32, self.as_bytes(), Case::Upper)
75 }
76}