From 1e607bbcc9c87ce815de2e3b77df91af34320a02 Mon Sep 17 00:00:00 2001 From: Dominic Date: Sun, 19 Apr 2020 22:26:29 +0200 Subject: [PATCH] more generous FromBody implementation --- gotham_restful/src/lib.rs | 9 +- gotham_restful_derive/src/from_body.rs | 129 ++++++++++++++++++------- 2 files changed, 102 insertions(+), 36 deletions(-) diff --git a/gotham_restful/src/lib.rs b/gotham_restful/src/lib.rs index e8ee7bc..0295a4b 100644 --- a/gotham_restful/src/lib.rs +++ b/gotham_restful/src/lib.rs @@ -55,7 +55,7 @@ Uploads and Downloads can also be handled, but you need to specify the mime type ```rust,no_run # #[macro_use] extern crate gotham_restful_derive; # use gotham::{router::builder::*, state::State}; -# use gotham_restful::{DrawResources, Raw, Resource, Success}; +# use gotham_restful::{DrawResources, Mime, Raw, Resource, Success}; # use serde::{Deserialize, Serialize}; #[derive(Resource)] #[rest_resource(create)] @@ -63,11 +63,14 @@ struct ImageResource; #[derive(FromBody, RequestBody)] #[supported_types(mime::IMAGE_GIF, mime::IMAGE_JPEG, mime::IMAGE_PNG)] -struct RawImage(Vec); +struct RawImage { + content: Vec, + content_type: Mime +} #[rest_create(ImageResource)] fn create(_state : &mut State, body : RawImage) -> Raw> { - Raw::new(body.0, mime::APPLICATION_OCTET_STREAM) + Raw::new(body.content, body.content_type) } # fn main() { # gotham::start("127.0.0.1:8080", build_simple_router(|route| { diff --git a/gotham_restful_derive/src/from_body.rs b/gotham_restful_derive/src/from_body.rs index 4119845..b3368ad 100644 --- a/gotham_restful_derive/src/from_body.rs +++ b/gotham_restful_derive/src/from_body.rs @@ -1,11 +1,15 @@ use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; -use quote::quote; +use quote::{format_ident, quote}; use syn::{ - spanned::Spanned, + punctuated::Punctuated, + token::Comma, Error, + Field, Fields, + Ident, ItemStruct, + Type, parse_macro_input }; @@ -16,6 +20,32 @@ pub fn expand_from_body(tokens : TokenStream) -> TokenStream .into() } +struct ParsedFields +{ + fields : Vec<(Ident, Type)>, + named : bool +} + +impl ParsedFields +{ + fn from_named(fields : Punctuated) -> Result + { + let fields = fields.into_iter().map(|field| (field.ident.unwrap(), field.ty)).collect(); + Ok(Self { fields, named: true }) + } + + fn from_unnamed(fields : Punctuated) -> Result + { + let fields = fields.into_iter().enumerate().map(|(i, field)| (format_ident!("arg{}", i), field.ty)).collect(); + Ok(Self { fields, named: false }) + } + + fn from_unit() -> Result + { + Ok(Self { fields: Vec::new(), named: false }) + } +} + fn expand(tokens : TokenStream) -> Result { let krate = super::krate(); @@ -23,45 +53,78 @@ fn expand(tokens : TokenStream) -> Result 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() })) - }, - _ => return Err(Error::new(fields.into_iter().nth(1).unwrap().span(), "FromBody can only be derived for structs with at most one field")) - } - }, - 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()))) - }, - _ => return Err(Error::new(fields.into_iter().nth(1).unwrap().span(), "FromBody can only be derived for structs with at most one field")) - } - }, - Fields::Unit => (quote!(), quote!(Self{})) + let fields = match input.fields { + Fields::Named(named) => ParsedFields::from_named(named.named)?, + Fields::Unnamed(unnamed) => ParsedFields::from_unnamed(unnamed.unnamed)?, + Fields::Unit => ParsedFields::from_unit()? }; + let mut where_clause = quote!(); + let mut block = quote!(); + let mut body_ident = format_ident!("_body"); + let mut type_ident = format_ident!("_type"); + + if let Some(body_field) = fields.fields.get(0) + { + body_ident = body_field.0.clone(); + let body_ty = &body_field.1; + where_clause = quote! { + #where_clause + #body_ty : for<'a> From<&'a [u8]>, + }; + block = quote! { + #block + let #body_ident : &[u8] = &#body_ident; + let #body_ident : #body_ty = #body_ident.into(); + }; + } + + if let Some(type_field) = fields.fields.get(1) + { + type_ident = type_field.0.clone(); + let type_ty = &type_field.1; + where_clause = quote! { + #where_clause + #type_ty : From<#krate::Mime>, + }; + block = quote! { + #block + let #type_ident : #type_ty = #type_ident.into(); + }; + } + + for field in &fields.fields[2..] + { + let field_ident = &field.0; + let field_ty = &field.1; + where_clause = quote! { + #where_clause + #field_ty : Default, + }; + block = quote! { + #block + let #field_ident : #field_ty = Default::default(); + }; + } + + let field_names : Vec<&Ident> = fields.fields.iter().map(|field| &field.0).collect(); + let ctor = if fields.named { + quote!(Self { #(#field_names),* }) + } else { + quote!(Self ( #(#field_names),* )) + }; + + // TODO: Replace the Err type with something more appropriate that implements Display Ok(quote! { impl #generics #krate::FromBody for #ident #generics - #were + where #where_clause { type Err = String; - fn from_body(body : #krate::gotham::hyper::body::Bytes, _content_type : #krate::Mime) -> Result + fn from_body(#body_ident : #krate::gotham::hyper::body::Bytes, #type_ident : #krate::Mime) -> Result { - let body : &[u8] = &body; - Ok(#body) + #block + Ok(#ctor) } } })