15 changed files with 236 additions and 203 deletions
@ -0,0 +1,13 @@ |
|||
[package] |
|||
name = "macros" |
|||
version = "0.1.0" |
|||
edition = "2021" |
|||
|
|||
[lib] |
|||
name = "macros" |
|||
path = "src/lib.rs" |
|||
proc-macro = true |
|||
|
|||
[dependencies] |
|||
quote = "1.0.38" |
|||
syn = "2.0.94" |
@ -0,0 +1,31 @@ |
|||
extern crate proc_macro; |
|||
|
|||
use proc_macro::TokenStream; |
|||
use quote::quote; |
|||
|
|||
#[proc_macro_derive(IdFromParam)] |
|||
pub fn derive_from_param(input: TokenStream) -> TokenStream { |
|||
let ast = syn::parse(input).unwrap(); |
|||
|
|||
impl_derive_macro(&ast) |
|||
} |
|||
|
|||
fn impl_derive_macro(ast: &syn::DeriveInput) -> TokenStream { |
|||
let name = &ast.ident; |
|||
let gen = quote! { |
|||
#[automatically_derived] |
|||
impl<'r> rocket::request::FromParam<'r> for #name { |
|||
type Error = (); |
|||
|
|||
#[inline(always)] |
|||
fn from_param(param: &'r str) -> Result<Self, Self::Error> { |
|||
if param.chars().all(|c| matches!(c, 'a'..='z' | 'A'..='Z' |'0'..='9' | '-')) { |
|||
Ok(Self(param.to_string())) |
|||
} else { |
|||
Err(()) |
|||
} |
|||
} |
|||
} |
|||
}; |
|||
gen.into() |
|||
} |
Loading…
Reference in new issue