1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-02-22 20:52:27 +00:00

more generous FromBody implementation

This commit is contained in:
Dominic 2020-04-19 22:26:29 +02:00
parent fdc34fc296
commit 1e607bbcc9
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
2 changed files with 102 additions and 36 deletions

View file

@ -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<u8>);
struct RawImage {
content: Vec<u8>,
content_type: Mime
}
#[rest_create(ImageResource)]
fn create(_state : &mut State, body : RawImage) -> Raw<Vec<u8>> {
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| {

View file

@ -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<Field, Comma>) -> Result<Self, Error>
{
let fields = fields.into_iter().map(|field| (field.ident.unwrap(), field.ty)).collect();
Ok(Self { fields, named: true })
}
fn from_unnamed(fields : Punctuated<Field, Comma>) -> Result<Self, Error>
{
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<Self, Error>
{
Ok(Self { fields: Vec::new(), named: false })
}
}
fn expand(tokens : TokenStream) -> Result<TokenStream2, Error>
{
let krate = super::krate();
@ -23,45 +53,78 @@ fn expand(tokens : TokenStream) -> Result<TokenStream2, Error>
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<Self, Self::Err>
fn from_body(#body_ident : #krate::gotham::hyper::body::Bytes, #type_ident : #krate::Mime) -> Result<Self, Self::Err>
{
let body : &[u8] = &body;
Ok(#body)
#block
Ok(#ctor)
}
}
})