Skip to content

Instantly share code, notes, and snippets.

@justinas
Last active April 7, 2016 22:35
Show Gist options
  • Save justinas/07244a127cd7a411632877641f9b5b50 to your computer and use it in GitHub Desktop.
Save justinas/07244a127cd7a411632877641f9b5b50 to your computer and use it in GitHub Desktop.
enum_len!
/// Defines an enum and implements a static function for it
/// that returns the number of variants it can take.
macro_rules! enum_len {
// 'Public API': 0 variants
($name:ident, []) => {
enum_len!($name, [], [], 0);
};
// 'Public API': 1 variant
($name:ident, [$first:ident]) => {
enum_len!($name, [$first,]);
};
// 'Public API': the normal case
// Trailing comma
($name:ident, [$first:ident, $($remainder:ident),*,]) => {
enum_len!($name, [$($remainder,)*], [$first], 1);
};
// No trailing comma
($name:ident, [$first:ident, $($remainder:ident),*]) => {
enum_len!($name, [$($remainder,)*], [$first], 1);
};
($name:ident, [$first:ident, $($remainder:ident,)*], [$($vars:ident),*], $cnt:expr) => {
enum_len!($name, [$($remainder,)*], [$($vars),*, $first], $cnt + 1);
};
($name:ident, [], [$($vars:ident),*], $cnt: expr) => {
enum $name {
$($vars),*
}
impl $name {
fn num_variants() -> usize {
$cnt
}
}
}
}
enum_len!(Direction, [North, East, South, West]);
fn main() {
println!("{}", Direction::num_variants());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment