From 1e4f1d0a6ae85db0c0766768ff8ffe72c50d5823 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 5 Jun 2025 08:52:18 +1000 Subject: [PATCH] Shrink code produced by `smallvec![]`. Currently `smallvec![]` expands to this: ``` { let count = 0usize; #[allow(unused_mut)] let mut vec = ::smallvec::SmallVec::new(); if count <= vec.capacity() { vec } else { ::smallvec::SmallVec::from_vec(::alloc::vec::Vec::new()) } }; ``` This commit adds a rule to the `smallvec!` macro for the zero-length case so it instead expands to this: ``` ::smallvec::SmallVec::new() ``` The `std::vec!` macro already has a similar special case. This commit also improves the non-zero case. - It removes the `#[allow(unused_mut)]`, which was only needed for the zero-length case. - It changes the `*` repetitions to `+`. (Again, like `std::vec`.) --- src/lib.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8ab158e..a2d1b7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2140,18 +2140,20 @@ impl Clone for IntoIter { macro_rules! smallvec { // count helper: transform any expression into 1 (@one $x:expr) => (1usize); + () => ( + $crate::SmallVec::new() + ); ($elem:expr; $n:expr) => ({ $crate::SmallVec::from_elem($elem, $n) }); - ($($x:expr),*$(,)?) => ({ - let count = 0usize $(+ $crate::smallvec!(@one $x))*; - #[allow(unused_mut)] + ($($x:expr),+$(,)?) => ({ + let count = 0usize $(+ $crate::smallvec!(@one $x))+; let mut vec = $crate::SmallVec::new(); if count <= vec.capacity() { $(vec.push($x);)* vec } else { - $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)*]) + $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+]) } }); }