-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
256 additions
and
50 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,17 @@ | ||
[package] | ||
name = "struct_morph" | ||
version = "0.1.0" | ||
version = "0.5.0" | ||
edition = "2021" | ||
license = "MIT" | ||
description = "a (proc) macro for morphing one struct into another." | ||
description = "macro for morphing one struct into another." | ||
authors = ["shrynx <[email protected]>"] | ||
repository = "https://github.com/shrynx/struct_morph/tree/main/lib" | ||
readme = "README.md" | ||
|
||
[lib] | ||
proc-macro = true | ||
|
||
[dependencies] | ||
syn = { version = "1.0", features = ["full"] } | ||
syn = { version = "2.0", features = ["full"] } | ||
quote = "1.0" | ||
proc-macro2 = "1.0" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,88 @@ | ||
# Struct Morph | ||
# Struct Morph [](https://github.com/shrynx/struct_morph/actions/workflows/rust.yml) [](https://crates.io/crates/struct_morph) | ||
|
||
A (proc) macro for morphing one struct into another. | ||
macro for morphing one struct into another. | ||
|
||
## Installation | ||
|
||
```sh | ||
cargo add struct_morph | ||
``` | ||
|
||
or manually | ||
|
||
```toml | ||
struct_morph = "0.5" | ||
``` | ||
|
||
## Usage | ||
|
||
I occasionally run into use case where i have two structs representing very similar data. They share most of the fields or can sometmes even be subset of one. | ||
Say we have a struct `ProductRow` coming from database and another struct `ProductInfo` which is what will be sent as a json from the api. | ||
|
||
```rust | ||
struct ProductRow { | ||
id: i32, | ||
name: String, | ||
description: String, | ||
available_count: i32, | ||
base_price: i32, | ||
discount: i32, | ||
created_at: DateTime, | ||
updated_at: DateTime, | ||
} | ||
|
||
struct ProductInfo { | ||
id: i32, | ||
name: String, | ||
description: String, | ||
is_available: bool, | ||
price: i32, | ||
} | ||
``` | ||
|
||
now for this small when we need to convert ProductRows to ProductInfos we can manually do it, but for larger structs it becomes quite mechanical. | ||
|
||
with this library you can write the following | ||
|
||
```rust | ||
use struct_morph::{morph, morph_field}; | ||
|
||
#[morph(ProductRow)] | ||
struct ProductInfo { | ||
id: i32, | ||
name: String, | ||
description: String, | ||
#[morph_field(transform = "is_available")] | ||
is_available: bool, | ||
#[morph_field(transform = "net_price")] | ||
price: i32, | ||
} | ||
|
||
fn is_available(value: &ProductRow) -> bool { | ||
value.available_count > 0 | ||
} | ||
|
||
fn net_price(value: &ProductRow) -> i32 { | ||
value.base_price - value.discount | ||
} | ||
``` | ||
|
||
and then you can simply generate a product info from a product row | ||
|
||
```rust | ||
let product_row: ProductRow = ProductRow { | ||
id: 10, | ||
name: "The Rust Programming Language".to_string(), | ||
description: "The official book on the Rust programming language".to_string(), | ||
available_count: 10, | ||
base_price: 50, | ||
discount: 10, | ||
created_at: DateTime::now(), | ||
updated_at: DateTime::now(), | ||
}; | ||
|
||
let product_info: ProductInfo = ProductInfo::from(product_row); | ||
``` | ||
|
||
This will copy the values for fields with same name (and type) and for the rest one can provide customer transform functions. | ||
It does so by implementing a `From` trait for the source and target struct. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,53 +1,140 @@ | ||
//! This crate provides macro for transforming value of one struct to another. | ||
//! | ||
//! ```edition2021 | ||
//! # use struct_morph::{morph, morph_field}; | ||
//! # | ||
//! # #[derive(Clone, Debug)] | ||
//! # struct ProductRow { | ||
//! # id: i32, | ||
//! # name: String, | ||
//! # description: String, | ||
//! # available_count: i32, | ||
//! # base_price: i32, | ||
//! # discount: i32 | ||
//! # } | ||
//! # | ||
//! # #[derive(Debug)] | ||
//! # #[morph(ProductRow)] | ||
//! # struct ProductInfo { | ||
//! # id: i32, | ||
//! # name: String, | ||
//! # description: String, | ||
//! # #[morph_field(transform = "is_available")] | ||
//! # is_available: bool, | ||
//! # #[morph_field(transform = "net_price")] | ||
//! # price: i32, | ||
//! # } | ||
//! # | ||
//! # fn is_available(value: &ProductRow) -> bool { | ||
//! # value.available_count > 0 | ||
//! # } | ||
//! # | ||
//! # fn net_price(value: &ProductRow) -> i32 { | ||
//! # value.base_price - value.discount | ||
//! # } | ||
//! # | ||
//! # fn main() { | ||
//! # let product_row: ProductRow = ProductRow { | ||
//! # id: 10, | ||
//! # name: "The Rust Programming Language".to_string(), | ||
//! # description: "The official book on the Rust programming language".to_string(), | ||
//! # available_count: 10, | ||
//! # base_price: 50, | ||
//! # discount: 10, | ||
//! # }; | ||
//! # | ||
//! # let product_info: ProductInfo = ProductInfo::from(product_row.clone()); | ||
//! # | ||
//! # println!("{:?}", product_row); | ||
//! # println!("{:?}", product_info); | ||
//! # } | ||
//! ``` | ||
//! | ||
//! Please refer to [https://github.com/shrynx/struct_morph/blob/main/README.md](README) for how to set this up. | ||
//! | ||
//! [https://github.com/shrynx/struct_morph]: https://github.com/shrynx/struct_morph | ||
use proc_macro::TokenStream; | ||
use quote::quote; | ||
use syn::{parse_macro_input, AttributeArgs, ItemStruct, NestedMeta}; | ||
use syn::{ | ||
parse::{Parse, ParseStream}, | ||
parse_macro_input, Ident, ItemStruct, LitStr, Token, | ||
}; | ||
|
||
struct MorphFieldArgs { | ||
transform_function_name: LitStr, | ||
} | ||
|
||
impl Parse for MorphFieldArgs { | ||
fn parse(input: ParseStream) -> syn::Result<Self> { | ||
let transform_keyword: Ident = input.parse()?; | ||
let _eq_token: Token![=] = input.parse()?; | ||
|
||
if transform_keyword != "transform" { | ||
return Err(syn::Error::new_spanned( | ||
transform_keyword, | ||
"Expected 'transform' followed by function name", | ||
)); | ||
} | ||
Ok(Self { | ||
transform_function_name: input.parse()?, | ||
}) | ||
} | ||
} | ||
|
||
#[proc_macro_attribute] | ||
pub fn morph_field(args: TokenStream, input: TokenStream) -> TokenStream { | ||
let _ = syn::parse_macro_input!(args as MorphFieldArgs); | ||
input | ||
} | ||
|
||
#[proc_macro_attribute] | ||
pub fn morph(attr: TokenStream, item: TokenStream) -> TokenStream { | ||
let args = parse_macro_input!(attr as AttributeArgs); | ||
let input = parse_macro_input!(item as ItemStruct); | ||
let source_struct_ident = parse_macro_input!(attr as Ident); | ||
let mut input = parse_macro_input!(item as ItemStruct); | ||
|
||
if args.len() != 1 { | ||
return syn::Error::new_spanned(&input, "Expected exactly one argument to morph") | ||
.to_compile_error() | ||
.into(); | ||
} | ||
let source_struct_ident = match &args[0] { | ||
NestedMeta::Meta(syn::Meta::Path(path)) if path.segments.len() == 1 => { | ||
&path.segments[0].ident | ||
} | ||
_ => { | ||
return syn::Error::new_spanned( | ||
&args[0], | ||
"Expected a single identifier as argument to morph", | ||
) | ||
.to_compile_error() | ||
.into() | ||
} | ||
}; | ||
let target_fields = &input | ||
.fields | ||
.iter() | ||
.map(|f| { | ||
let field_name = &f.ident; | ||
let transform_function = f.attrs.iter().find_map(|attr| { | ||
attr.path().is_ident("morph_field").then(|| { | ||
let args: MorphFieldArgs = attr.parse_args().unwrap(); | ||
args.transform_function_name.value() | ||
}) | ||
}); | ||
|
||
match transform_function { | ||
Some(func) => { | ||
let func_ident = Ident::new(&func, proc_macro2::Span::call_site()); | ||
quote! { #field_name: #func_ident(&source) } | ||
} | ||
None => quote! { #field_name: source.#field_name.clone() }, | ||
} | ||
}) | ||
.collect::<Vec<_>>(); | ||
|
||
let target_struct_ident = &input.ident; | ||
let fields = input.fields.iter().map(|f| { | ||
let field_name = &f.ident; | ||
quote! { | ||
#field_name: source.#field_name.clone() | ||
} | ||
}); | ||
|
||
let gen = quote! { | ||
let from_trait_gen = quote! { | ||
impl From<#source_struct_ident> for #target_struct_ident { | ||
fn from(source: #source_struct_ident) -> Self { | ||
Self { | ||
#(#fields),* | ||
#(#target_fields),* | ||
} | ||
} | ||
} | ||
}; | ||
|
||
let expanded = quote! { | ||
#input | ||
#gen | ||
}; | ||
input.fields.iter_mut().for_each(|field| { | ||
field | ||
.attrs | ||
.retain(|attr| !attr.path().is_ident("morph_field")); | ||
}); | ||
|
||
TokenStream::from(expanded) | ||
TokenStream::from(quote! { | ||
#input | ||
#from_trait_gen | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,67 @@ | ||
extern crate struct_morph; | ||
|
||
use struct_morph::morph; | ||
|
||
#[derive(Clone)] | ||
struct Foo { | ||
a: u16, | ||
b: &'static str, | ||
b: String, | ||
c: Vec<u32>, | ||
d: (&'static str, &'static str), | ||
d: (String, String), | ||
} | ||
|
||
#[morph(Foo)] | ||
struct Bar { | ||
a: u16, | ||
b: &'static str, | ||
b: String, | ||
c: Vec<u32>, | ||
} | ||
|
||
#[test] | ||
fn it_works() { | ||
fn simple() { | ||
let my_foo: Foo = Foo { | ||
a: 10, | ||
b: "Hello", | ||
b: "Hello".to_string(), | ||
c: vec![1, 3, 4], | ||
d: ("Good", "Bye"), | ||
d: ("Good".to_string(), "Bye".to_string()), | ||
}; | ||
|
||
let auto_bar: Bar = Bar::from(my_foo.clone()); | ||
|
||
assert_eq!(my_foo.a, auto_bar.a); | ||
assert_eq!(my_foo.b, auto_bar.b); | ||
assert_eq!(my_foo.c, auto_bar.c); | ||
} | ||
|
||
#[morph(Foo)] | ||
struct Baz { | ||
b: String, | ||
c: Vec<u32>, | ||
#[morph_field(transform = "foo_d_first")] | ||
e: String, | ||
#[morph_field(transform = "foo_d_sec_len")] | ||
f: usize, | ||
} | ||
|
||
fn foo_d_first(value: &Foo) -> String { | ||
value.d.0.clone() | ||
} | ||
|
||
fn foo_d_sec_len(value: &Foo) -> usize { | ||
value.d.1.len() | ||
} | ||
|
||
#[test] | ||
fn with_field_transform() { | ||
let my_foo: Foo = Foo { | ||
a: 10, | ||
b: "Hello".to_string(), | ||
c: vec![1, 3, 4], | ||
d: ("Good".to_string(), "Bye".to_string()), | ||
}; | ||
|
||
let auto_baz: Baz = Baz::from(my_foo.clone()); | ||
|
||
assert_eq!(my_foo.b, auto_baz.b); | ||
assert_eq!(my_foo.c, auto_baz.c); | ||
assert_eq!(foo_d_first(&my_foo), auto_baz.e); | ||
assert_eq!(foo_d_sec_len(&my_foo), auto_baz.f); | ||
} |