Skip to content

Instantly share code, notes, and snippets.

@sagebind
Last active April 9, 2017 21:15
Show Gist options
  • Save sagebind/f520397ba8b2c8f4d00ed17a95959190 to your computer and use it in GitHub Desktop.
Save sagebind/f520397ba8b2c8f4d00ed17a95959190 to your computer and use it in GitHub Desktop.
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