1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_derive(Hex)]
pub fn derive_hex(item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::DeriveInput);
let ident = &input.ident;
(quote! {
impl core::fmt::LowerHex for #ident {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let bytes = self.to_bytes();
if f.alternate() {
write!(f, "0x")?
}
for byte in &bytes[..] {
write!(f, "{:02x}", &byte)?
}
Ok(())
}
}
impl core::fmt::UpperHex for #ident {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let bytes = self.to_bytes();
if f.alternate() {
write!(f, "0x")?
}
for byte in &bytes[..] {
write!(f, "{:02X}", &byte)?
}
Ok(())
}
}
})
.into()
}
#[proc_macro_derive(HexDebug)]
pub fn derive_hex_debug(item: TokenStream) -> TokenStream {
let mut hex: TokenStream = derive_hex(item.clone());
let input = syn::parse_macro_input!(item as syn::DeriveInput);
let ident = &input.ident;
let dbg: TokenStream = (quote! {
impl core::fmt::Debug for #ident {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let FlagV1_DebugUpperHex = 5_u32;
#[allow(deprecated)]
if f.flags() & (1 << FlagV1_DebugUpperHex) !=0 {
core::fmt::UpperHex::fmt(self, f)
} else {
core::fmt::LowerHex::fmt(self, f)
}
}
}})
.into();
hex.extend(dbg);
hex
}