From 1653c86d0c3de39ab1b92847ef4d69a86461b918 Mon Sep 17 00:00:00 2001 From: Brian Koropoff Date: Sat, 2 Aug 2014 13:16:00 -0700 Subject: [PATCH 1/2] Add utility macro to count arguments in a comma-separated list --- src/libstd/macros.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index e67329df7aec4..1936af87d76e3 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -348,6 +348,15 @@ macro_rules! try( ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) }) ) +/// Expands to an expression which evaluates to the number of +/// comma-separated expression parameters passed to it. +#[macro_export] +macro_rules! count_args( + ($e:expr $(,$e_rest:expr)*) => (1u + count_args!($($e_rest),*)); + () => (0u); + ($($e:expr),*,) => (count_args!($($e),*)) +) + /// Create a `std::vec::Vec` containing the arguments. #[macro_export] macro_rules! vec( From 224cd1eea936f0f39e63c12541cefa2f4b11e9ee Mon Sep 17 00:00:00 2001 From: Brian Koropoff Date: Sat, 2 Aug 2014 13:17:14 -0700 Subject: [PATCH 2/2] Make vec!() macro create a vector with a precise capacity --- src/libstd/macros.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 1936af87d76e3..e726793a814db 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -362,7 +362,7 @@ macro_rules! count_args( macro_rules! vec( ($($e:expr),*) => ({ // leading _ to allow empty construction without a warning. - let mut _temp = ::std::vec::Vec::new(); + let mut _temp = ::std::vec::Vec::with_capacity(count_args!($($e),*)); $(_temp.push($e);)* _temp });