2019-10-20 14:49:53 +00:00
|
|
|
use proc_macro::TokenStream;
|
2020-04-08 21:53:57 +02:00
|
|
|
use proc_macro2::TokenStream as TokenStream2;
|
2019-10-20 14:49:53 +00:00
|
|
|
use quote::quote;
|
|
|
|
use syn::{
|
2020-04-08 21:53:57 +02:00
|
|
|
spanned::Spanned,
|
|
|
|
Error,
|
2019-10-20 14:49:53 +00:00
|
|
|
Fields,
|
|
|
|
ItemStruct,
|
|
|
|
parse_macro_input
|
|
|
|
};
|
|
|
|
|
|
|
|
pub fn expand_from_body(tokens : TokenStream) -> TokenStream
|
2020-04-08 21:53:57 +02:00
|
|
|
{
|
|
|
|
expand(tokens)
|
|
|
|
.unwrap_or_else(|err| err.to_compile_error())
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn expand(tokens : TokenStream) -> Result<TokenStream2, Error>
|
2019-10-20 14:49:53 +00:00
|
|
|
{
|
|
|
|
let krate = super::krate();
|
2020-04-08 21:53:57 +02:00
|
|
|
let input = parse_macro_input::parse::<ItemStruct>(tokens)?;
|
2019-10-20 14:49:53 +00:00
|
|
|
let ident = input.ident;
|
|
|
|
let generics = input.generics;
|
|
|
|
|
|
|
|
let (were, body) = match input.fields {
|
|
|
|
Fields::Named(named) => {
|
|
|
|
let fields = named.named;
|
|
|
|
match fields.len() {
|
|
|
|
0 => (quote!(), quote!(Self{})),
|
|
|
|
1 => {
|
|
|
|
let field = fields.first().unwrap();
|
|
|
|
let field_ident = field.ident.as_ref().unwrap();
|
|
|
|
let field_ty = &field.ty;
|
|
|
|
(quote!(where #field_ty : for<'a> From<&'a [u8]>), quote!(Self { #field_ident: body.into() }))
|
|
|
|
},
|
2020-04-08 21:53:57 +02:00
|
|
|
_ => return Err(Error::new(fields.into_iter().nth(1).unwrap().span(), "FromBody can only be derived for structs with at most one field"))
|
2019-10-20 14:49:53 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
Fields::Unnamed(unnamed) => {
|
|
|
|
let fields = unnamed.unnamed;
|
|
|
|
match fields.len() {
|
|
|
|
0 => (quote!(), quote!(Self{})),
|
|
|
|
1 => {
|
|
|
|
let field = fields.first().unwrap();
|
|
|
|
let field_ty = &field.ty;
|
|
|
|
(quote!(where #field_ty : for<'a> From<&'a [u8]>), quote!(Self(body.into())))
|
|
|
|
},
|
2020-04-08 21:53:57 +02:00
|
|
|
_ => return Err(Error::new(fields.into_iter().nth(1).unwrap().span(), "FromBody can only be derived for structs with at most one field"))
|
2019-10-20 14:49:53 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
Fields::Unit => (quote!(), quote!(Self{}))
|
|
|
|
};
|
|
|
|
|
2020-04-08 21:53:57 +02:00
|
|
|
Ok(quote! {
|
2019-10-20 14:49:53 +00:00
|
|
|
impl #generics #krate::FromBody for #ident #generics
|
|
|
|
#were
|
|
|
|
{
|
|
|
|
type Err = String;
|
|
|
|
|
2020-04-15 23:20:41 +02:00
|
|
|
fn from_body(body : #krate::gotham::hyper::body::Bytes, _content_type : #krate::Mime) -> Result<Self, Self::Err>
|
2019-10-20 14:49:53 +00:00
|
|
|
{
|
|
|
|
let body : &[u8] = &body;
|
|
|
|
Ok(#body)
|
|
|
|
}
|
|
|
|
}
|
2020-04-08 21:53:57 +02:00
|
|
|
})
|
2019-10-20 14:49:53 +00:00
|
|
|
}
|