Skip to content

Instantly share code, notes, and snippets.

@bstrie
Last active August 29, 2015 14:01
Show Gist options
  • Save bstrie/9f1f228f859ebd1a5361 to your computer and use it in GitHub Desktop.
Save bstrie/9f1f228f859ebd1a5361 to your computer and use it in GitHub Desktop.
#![feature(macro_rules)]
macro_rules! vec_new(
($($e:expr),*) => ({
// leading _ to allow empty construction without a warning.
let mut _temp = ::std::vec::Vec::with_capacity(arity!($($e),*));
$(_temp.push($e);)*
_temp
});
($($e:expr),+,) => (vec_new!($($e),+))
)
// Trust me, you *really* want the helper macros...
// If you attempt this without them, may God have mercy on your soul.
macro_rules! arity(
($($thing:expr),+) => (arity_expr!($($thing),*));
($($thing:pat),+) => (arity_pat!($($thing),*));
() => (0);
)
macro_rules! arity_expr(
($head:expr, $($tail:expr),*) => (1 + arity_expr!($($tail),*));
($last:expr) => (1);
)
macro_rules! arity_pat(
($head:pat, $($tail:pat),*) => (1 + arity_pat!($($tail),*));
($last:pat) => (1);
)
fn test_arity() {
assert!(arity!() == 0);
// expr
assert!(arity!(9) == 1);
assert!(arity!(9,9,9) == 3);
// ident - matched by expr
assert!(arity!(Nine) == 1);
assert!(arity!(Nine,Nine,Nine) == 3);
// ty - matched by expr
assert!(arity!(Option::<int>) == 1);
assert!(arity!(Option::<int>,Option::<int>,Option::<int>) == 3);
// block - matched by expr
assert!(arity!({9;9}) == 1);
assert!(arity!({9;9},{9;9},{9;9}) == 3);
// pat
assert!(arity!(foo @ _) == 1);
assert!(arity!(foo @ _,foo @ _,foo @ _) == 3);
println!("All tests pass");
}
fn main() {
test_arity();
let v = vec_new![7,8,9];
println!("{}", v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment