zenoh_ros_derive/
lib.rs

1#[proc_macro_derive(ZBytesCdr)]
2pub fn zbytes_cdr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
3    // Parse the input token stream into a syntax tree
4    let input = syn::parse_macro_input!(input as syn::DeriveInput);
5
6    // Extract the struct's name
7    let name = input.ident;
8
9    let expanded = quote::quote! {
10        impl From<#name> for zenoh::bytes::ZBytes {
11            fn from(msg: #name) -> Self {
12                let payload = cdr::serialize::<_, _, cdr::CdrLe>(&msg, cdr::Infinite).unwrap();
13                payload.into()
14            }
15        }
16        impl From<&#name> for zenoh::bytes::ZBytes {
17            fn from(msg: &#name) -> Self {
18                let payload = cdr::serialize::<_, _, cdr::CdrLe>(msg, cdr::Infinite).unwrap();
19                payload.into()
20            }
21        }
22
23        impl From<zenoh::bytes::ZBytes> for #name {
24            fn from(bytes: zenoh::bytes::ZBytes) -> Self {
25                cdr::deserialize(&bytes.to_bytes()).unwrap()
26            }
27        }
28        impl From<&zenoh::bytes::ZBytes> for #name {
29            fn from(bytes: &zenoh::bytes::ZBytes) -> Self {
30                cdr::deserialize(&(*bytes).to_bytes()).unwrap()
31            }
32        }
33    };
34
35    proc_macro::TokenStream::from(expanded)
36}