Skip to content

Commit

Permalink
derive: less tokenstream conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
jordens committed Sep 23, 2024
1 parent 17b8bae commit 2d9918c
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions miniconf_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,49 +9,56 @@ use tree::Tree;
#[proc_macro_derive(TreeKey, attributes(tree))]
pub fn derive_tree_key(input: TokenStream) -> TokenStream {
match Tree::parse(&parse_macro_input!(input as DeriveInput)) {
Ok(t) => t.tree_key().into(),
Err(e) => e.write_errors().into(),
Ok(t) => t.tree_key(),
Err(e) => e.write_errors(),
}
.into()
}

/// Derive the `TreeSerialize` trait for a struct.
#[proc_macro_derive(TreeSerialize, attributes(tree))]
pub fn derive_tree_serialize(input: TokenStream) -> TokenStream {
match Tree::parse(&parse_macro_input!(input as DeriveInput)) {
Ok(t) => t.tree_serialize().into(),
Err(e) => e.write_errors().into(),
Ok(t) => t.tree_serialize(),
Err(e) => e.write_errors(),
}
.into()
}

/// Derive the `TreeDeserialize` trait for a struct.
#[proc_macro_derive(TreeDeserialize, attributes(tree))]
pub fn derive_tree_deserialize(input: TokenStream) -> TokenStream {
match Tree::parse(&parse_macro_input!(input as DeriveInput)) {
Ok(t) => t.tree_deserialize().into(),
Err(e) => e.write_errors().into(),
Ok(t) => t.tree_deserialize(),
Err(e) => e.write_errors(),
}
.into()
}

/// Derive the `TreeAny` trait for a struct.
#[proc_macro_derive(TreeAny, attributes(tree))]
pub fn derive_tree_any(input: TokenStream) -> TokenStream {
match Tree::parse(&parse_macro_input!(input as DeriveInput)) {
Ok(t) => t.tree_any().into(),
Err(e) => e.write_errors().into(),
Ok(t) => t.tree_any(),
Err(e) => e.write_errors(),
}
.into()
}

/// Shorthand to derive the `TreeKey`, `TreeAny`, `TreeSerialize`, and `TreeDeserialize` traits for a struct.
#[proc_macro_derive(Tree, attributes(tree))]
pub fn derive_tree(input: TokenStream) -> TokenStream {
match Tree::parse(&parse_macro_input!(input as DeriveInput)) {
Ok(t) => {
let mut ts: TokenStream = t.tree_key().into();
ts.extend(TokenStream::from(t.tree_any()));
ts.extend(TokenStream::from(t.tree_serialize()));
ts.extend(TokenStream::from(t.tree_deserialize()));
ts
}
Err(e) => e.write_errors().into(),
Ok(t) => [
t.tree_key(),
t.tree_any(),
t.tree_serialize(),
t.tree_deserialize(),
]
.into_iter()
.flatten()
.collect(),
Err(e) => e.write_errors(),
}
.into()
}

0 comments on commit 2d9918c

Please sign in to comment.