rpcx_derive/
lib.rs

1#![recursion_limit = "128"]
2
3extern crate proc_macro;
4
5use proc_macro::TokenStream;
6use quote::quote;
7use syn::{parse_macro_input, DeriveInput};
8
9#[proc_macro_derive(RpcxParam)]
10pub fn rpcx_param(input: TokenStream) -> TokenStream {
11    let input = parse_macro_input!(input as DeriveInput);
12
13    let name = input.ident;
14
15    let expanded = quote! {
16        impl RpcxParam for #name {
17            fn into_bytes(&self, st: SerializeType) -> Result<Vec<u8>> {
18                match st {
19                    SerializeType::JSON => serde_json::to_vec(self).map_err(|err| Error::from(err)),
20                    SerializeType::MsgPack => {
21                        rmps::to_vec(self).map_err(|err| Error::new(ErrorKind::Other, err.description()))
22                    }
23                    _ => Err(Error::new(ErrorKind::Other, "unknown format")),
24                }
25            }
26            fn from_slice(&mut self, st: SerializeType, data: &[u8]) -> Result<()> {
27                match st {
28                    SerializeType::JSON => {
29                        let param: Self = serde_json::from_slice(data)?;
30                        *self = param;
31                        Ok(())
32                    }
33                    SerializeType::MsgPack => {
34                        let param: Self = rmps::from_slice(data)
35                            .map_err(|err| Error::new(ErrorKind::Other, err.description()))?;
36                        *self = param;
37                        Ok(())
38                    }
39                    _ => Err(Error::new(ErrorKind::Other, "unknown format")),
40                }
41            }
42        }
43    };
44
45    // Hand the output tokens back to the compiler
46    TokenStream::from(expanded)
47}