From 1038b13dbb7f696d8752a9cea408e51985544133 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Sat, 3 Oct 2026 00:23:54 -0700 Subject: [PATCH] When collecting into a ThinVec, pass the size hint to `with_capacity` This ensures that collecting from an iterator with a good size hint will avoid creating a ThinVec with excess capacity. In particular, collecting 1-3 items into a ThinVec will no longer create a ThinVec with capacity 4. --- src/lib.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 3cf70d3..97fb92b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2371,7 +2371,8 @@ impl Default for ThinVec { impl FromIterator for ThinVec { #[inline] fn from_iter>(iter: I) -> ThinVec { - let mut vec = ThinVec::new(); + let iter = iter.into_iter(); + let mut vec = ThinVec::with_capacity(iter.size_hint().0); vec.extend(iter); vec } @@ -3600,6 +3601,15 @@ mod tests { } } + #[test] + fn test_collect_capacity() { + for i in 0..20 { + let v = (0..i).into_iter().collect::>(); + assert_eq!(v.len(), i); + assert_eq!(v.capacity(), i); + } + } + #[test] fn test_clone() { let mut v = ThinVec::::new();