Model Mapper
This library provides a macro to implement From and/or TryFrom trait between types (both enums and structs) without boilerplate.
It also provides a with module containing some utilities to convert between types that does not implement Into trait.
Usage
A mapper attribute is required at type-level and it's optional at field or variant level.
The following attributes are available.
-
Type level attributes:
ty = PathType(mandatory): The other type to derive the conversionignore(optional, multiple): Additional fields (for structs with named fields) or variants (for enums) the other type has and this one doesn't *field = String(mandatory): The field or variant to ignoredefault = Expr(optional): The default value (defaults toDefault::default())
from(optional): Wether to deriveFromthe other type for selfinto(optional): Wether to deriveFromself for the other typetry_from(optional): Wether to deriveTryFromthe other type for selftry_into(optional): Wether to deriveTryFromself for the other type
-
Variant level attributes:
ignore(optional, multiple): Additional fields of the variant that the other type variant has and this one doesn't *field = String(mandatory): The field or variant to ignoredefault = Expr(optional): The default value (defaults toDefault::default())
skip(optional): Wether to skip this variant because the other enum doesn't have it *default = Expr(optional): If skipped, the default value to populate this variant (defaults toDefault::default())rename = "OtherVariant"(optional): To rename this variant on the other enum
-
Field level attributes:
skip(optional): Wether to skip this field because the other type doesn't have it *default = Expr(optional): If skipped, the default value to populate this field (defaults toDefault::default())rename = "other_field"(optional): To rename this field on the other typewith = mod::my_function(optional): If the field type doesn't implementIntothe other, this property allows you to customize the behavior by providing a conversion functiontry_with = mod::my_function(optional): If the field type doesn't implementTryIntothe other, this property allows you to customize the behavior by providing a conversion function
* When ignoring or skipping fields or variants it might be required that the enum or the field type implements
Default in order to properly populate it if no default value is provided.
Attributes can be set directly if only one type is involved in the conversion:
Or they can be wrapped in a derive attribute to allow for multiple conversions:
If multiple conversions are involved, both variant and field level attributes can also be wrapped in a when attribute
and must set the ty they refer to:
Example
The macro expansion above would generate something like:
There are more examples available in the integration tests.