1use proc_macro::TokenStream;
2use syn::{DeriveInput, Data, DataStruct, Fields};
3use quote::quote;
4use heck::MixedCase;
5
6#[proc_macro_derive(Dto)]
7pub fn dto_derive(input: TokenStream) -> TokenStream {
8 let ast: DeriveInput = syn::parse(input)
9 .expect(" -- parse err at derive dto ");
10
11 let name = &ast.ident.clone();
12 let fields = match &ast.data {
13 Data::Struct(DataStruct {
14 fields: Fields::Named(fields),
15 ..
16 }) => &fields.named,
17 _ => panic!(" -- analysis fields err at derive dto "),
18 };
19
20 let itm = fields.iter().map(|field| {
21 let field_name = field.ident.clone().unwrap();
22 let mix = field_name.to_string().to_mixed_case();
23
24 quote! {
25 if let Some(s) = &self.#field_name {
26 map.insert(#mix.to_string() , s.to_string());
27 }
28 }
29 });
30
31 TokenStream::from(quote! {
32 impl Dto for #name {
33 fn mapping(&self, map: &mut HashMap<String, String>) {
34 #(
35 #itm
36 )*
37 }
38 }
39 })
40}
41