Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make vec!() macro create a vector with precise capacity #16204

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/libstd/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,21 @@ 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),*));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pattern looks weird, shouldn't it be ($e:expr, $(e_rest:expr),*)?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That doesn't work with one argument i.e. count_args!(foo).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah. You can always add a one-argument case though. But I suppose if this pattern works, then it doesn't matter.

() => (0u);
($($e:expr),*,) => (count_args!($($e),*))
)

/// Create a `std::vec::Vec` containing the arguments.
#[macro_export]
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
});
Expand Down