#[proc_macro]
pub fn cbor(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let reconstructed = format!("{}", &input);
let parsed = cbor_diag::parse_diag(reconstructed).expect("Error parsing CBOR literal");
let binary = parsed.to_bytes();
let input_spans: Option<Vec<_>> = input
.into_iter()
.map(|tree| tree.span().source_text())
.collect();
if let Some(parts) = input_spans {
let joint = parts.join("");
let source_parsed =
cbor_diag::parse_diag(joint).expect("CBOR from source is invalid, but stringified token tree was valid. This is possibly a bug in cbor-macro. As a workaround, you can use the cbo!(R#\"...\"#) macro.");
if source_parsed.to_bytes() != binary {
panic!("CBOR got misrepresented by Rust tokenization and re-stringification. Use cbo!(r#\"...\"#) instead.");
}
} else {
panic!("Some parts of the CBOR expression were not found in source files, CBOR could not be verified. Use cbo!(r#\"...\") instead.")
}
proc_macro::TokenStream::from(quote::quote! {
unsafe { cboritem::CborItem::new(&[ #(#binary),* ])
} })
}
#[proc_macro]
pub fn cbo(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::LitStr);
let parsed = cbor_diag::parse_diag(input.value()).expect("Error parsing CBOR literal");
let binary = parsed.to_bytes();
proc_macro::TokenStream::from(quote::quote! {
unsafe { cboritem::CborItem::new(&[ #(#binary),* ])
} })
}
#[proc_macro]
pub fn pretty(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let hex = syn::parse_macro_input!(input as syn::LitStr);
let parsed = cbor_diag::parse_hex(hex.value()).expect("CBOR is not well-formed");
let binary = parsed.to_bytes();
proc_macro::TokenStream::from(quote::quote! {
unsafe { cboritem::CborItem::new(&[ #(#binary),* ])
} })
}
#[proc_macro]
pub fn pretty_bytes(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let hex = syn::parse_macro_input!(input as syn::LitStr);
let comment = regex::RegexBuilder::new("#.*$")
.multi_line(true)
.build()
.unwrap();
let space = regex::Regex::new("[[:space:]]").unwrap();
let hex = hex.value();
let hex = comment.replace_all(&hex, "");
let hex = space.replace_all(&hex, "");
let hex: &str = hex.as_ref();
let binary = hex::decode(hex).expect("Invalid hex");
proc_macro::TokenStream::from(quote::quote! {
{
let result = &[ #(#binary),* ];
result
}
})
}