sbs_api_macro/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, Data, DeriveInput};
4
5#[proc_macro_derive(Serialize)]
6pub fn derive_serialize(input: TokenStream) -> TokenStream {
7    let input = parse_macro_input!(input as DeriveInput);
8    let name = input.ident;
9
10    let out = match input.data {
11        Data::Struct(s) => {
12            let fields = s.fields.into_iter().map(|field| field.ident.unwrap());
13            quote! {
14                impl ::sbs_api::Serialize for #name {
15                    fn serialize(&self, sbi: &mut ::sbs_api::SBI) {
16                        #(
17                            Serialize::serialize(&self.#fields, sbi);
18                        )*
19                    }
20                }
21            }
22        },
23        _ => todo!()
24    };
25
26    out.into()
27}
28
29#[proc_macro_derive(DeSerialize)]
30pub fn derive_deserialize(input: TokenStream) -> TokenStream {
31    let input = parse_macro_input!(input as DeriveInput);
32    let name = input.ident;
33
34    let out = match input.data {
35        Data::Struct(s) => {
36            let fields = s.fields.clone().into_iter().map(|field| field.ident.unwrap());
37            let types = s.fields.clone().into_iter().map(|field| field.ty);
38            quote! {
39                impl ::sbs_api::DeSerialize for #name {
40                    fn deserialize(sbi: &mut ::sbs_api::SBI, offset: &mut usize) -> Result<Self, ()> where Self: Sized {
41                        Ok(Self {
42                            #(  
43                                #fields: #types ::deserialize(sbi, offset)?,
44                            )*
45                        })
46                    }
47                }
48            }
49        },
50        _ => todo!()
51    };
52
53    out.into()
54}