Last active
April 9, 2017 21:15
-
-
Save sagebind/f520397ba8b2c8f4d00ed17a95959190 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
pub trait CodeValue: Sized { | |
fn value(&self) -> &str; | |
fn from_value(value: &str) -> Option<Self>; | |
} | |
macro_rules! code_value_enum { | |
( | |
$NAME:ident { | |
$( | |
$VARIANT:ident => $OUT:expr; { | |
$( | |
<= $IN:expr | |
),* | |
} | |
),* | |
} | |
) => ( | |
#[derive(Clone, Copy, Debug)] | |
pub enum $NAME { | |
$( | |
$VARIANT, | |
)* | |
} | |
impl CodeValue for $NAME { | |
fn value(&self) -> &str { | |
match *self { | |
$( | |
$NAME::$VARIANT => $OUT, | |
)* | |
} | |
} | |
fn from_value(value: &str) -> Option<$NAME> { | |
match value { | |
$( | |
$( | |
$IN | |
)|* => Some($NAME::$VARIANT), | |
)* | |
_ => None, | |
} | |
} | |
} | |
); | |
} | |
code_value_enum! { | |
Foo { | |
Variant1 => "Variant 1"; { | |
<= "V1", | |
<= "Variant 1" | |
} | |
} | |
} | |
fn main() { | |
println!("{}", Foo::Variant1.value()); | |
println!("{:?}", Foo::from_value("V1")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment