From c3159c2b59ffa8083c9def22285251430cfd8b88 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 6 Jun 2025 15:46:44 +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 8689b75..3259774 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -184,18 +184,20 @@ use core::mem::ManuallyDrop; 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.inline_size() { $(vec.push($x);)* vec } else { - $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)*]) + $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+]) } }); }