Skip to content

Commit

Permalink
[fix] #1917: Added easy_from_str_impl macro for use with AssetValueType
Browse files Browse the repository at this point in the history
Signed-off-by: Sam H. Smith <[email protected]>
  • Loading branch information
SamHSmith committed Apr 4, 2022
1 parent af5c8c2 commit 84ea691
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions data_model/src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,31 @@ pub enum AssetValueType {
Store,
}

impl FromStr for AssetValueType {
type Err = &'static str;

fn from_str(value_type: &str) -> Result<Self, Self::Err> {
// TODO: Could be implemented with some macro
match value_type {
"Quantity" => Ok(AssetValueType::Quantity),
"BigQuantity" => Ok(AssetValueType::BigQuantity),
"Fixed" => Ok(AssetValueType::Fixed),
"Store" => Ok(AssetValueType::Store),
_ => Err("Unknown variant"),
/// A declarative macro that implements FromStr for a given
/// C like enumeration. The macro is invoked like follows:
/// `easy_from_str_impl! { NameOfEnum, EnumVariation1, EnumVariation2, ... }`
macro_rules! easy_from_str_impl {
(eval_to $cmp:expr, $enum_type:ty, $enum_value:tt) => {
if $cmp == stringify!($enum_value) {
return Ok(<$enum_type>::$enum_value);
}
}
};
($enum_type:ty, $( $enum_value:tt ),+ ) => {
impl FromStr for AssetValueType {
type Err = &'static str;

fn from_str(value_type: &str) -> Result<Self, Self::Err> {
$(
easy_from_str_impl!{eval_to value_type, $enum_type, $enum_value}
)+
return Err("Unknown variant");
}
}
};
}

easy_from_str_impl! {AssetValueType, Quantity, BigQuantity, Fixed, Store}

/// Asset's inner value.
#[derive(
Debug, Clone, PartialEq, Eq, Decode, Encode, Deserialize, Serialize, FromVariant, IntoSchema,
Expand Down

0 comments on commit 84ea691

Please sign in to comment.