diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 3782f9e95194c..ac263ccaca839 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -3543,11 +3543,12 @@ impl Vec { // for item in iterator { // self.push(item); // } - while let Some(element) = iterator.next() { + let (lower, _) = iterator.size_hint(); + let initial_len = self.len(); + iterator.for_each(move |element| { let len = self.len(); if len == self.capacity() { - let (lower, _) = iterator.size_hint(); - self.reserve(lower.saturating_add(1)); + self.reserve(lower.saturating_sub(len - initial_len).saturating_add(1)); } unsafe { ptr::write(self.as_mut_ptr().add(len), element); @@ -3556,7 +3557,7 @@ impl Vec { // NB can't overflow since we would have had to alloc the address space self.set_len(len + 1); } - } + }); } // specific extend for `TrustedLen` iterators, called both by the specializations