Skip to content

Commit

Permalink
feat: app state derive macro (#180)
Browse files Browse the repository at this point in the history
  • Loading branch information
elcharitas authored Sep 3, 2024
1 parent 794da88 commit fbb5847
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions crates/macros/src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ pub mod inject;
pub mod injectable;
pub mod route;
pub mod routes;
pub mod state;
19 changes: 19 additions & 0 deletions crates/macros/src/common/state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use proc_macro::TokenStream;

pub(crate) fn derive_app_state_macro(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as syn::ItemStruct);
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

let expanded = quote::quote! {
impl shared::server::context::AppState for #name #impl_generics #ty_generics #where_clause {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
};
TokenStream::from(expanded)
}
14 changes: 14 additions & 0 deletions crates/macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,3 +387,17 @@ pub fn query_derive_macro(input: TokenStream) -> TokenStream {
pub fn param_derive_macro(input: TokenStream) -> TokenStream {
param_macro(input)
}

#[proc_macro_derive(AppState)]
/// The `AppState` derive macro is used to derive a struct that can be used as a state in a server.
///
/// ### Example
/// ```rust ignore
/// #[derive(AppState)]
/// struct MyState {
/// // fields
/// }
/// ```
pub fn app_state_derive_macro(input: TokenStream) -> TokenStream {
common::state::derive_app_state_macro(input)
}

0 comments on commit fbb5847

Please sign in to comment.