Skip to content

Commit 2ca7b7e

Browse files
authored
Rollup merge of rust-lang#66341 - crgl:vec-deque-extend, r=Amanieu
Match `VecDeque::extend` to `Vec::extend_desugared` Currently, `VecDeque::extend` [does not reserve at all](rust-lang#65069 (comment)). This implementation still runs a check every iteration of the loop, but should reallocate at most once for the common cases where the `size_hint` lower bound is exact. Further optimizations in the future could improve this for some common cases, but given the complexity of the `Vec::extend` implementation it's not immediately clear that this would be worthwhile.
2 parents 3eeb8d4 + 164d1a2 commit 2ca7b7e

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/liballoc/collections/vec_deque.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -2809,7 +2809,22 @@ impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
28092809
#[stable(feature = "rust1", since = "1.0.0")]
28102810
impl<A> Extend<A> for VecDeque<A> {
28112811
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
2812-
iter.into_iter().for_each(move |elt| self.push_back(elt));
2812+
// This function should be the moral equivalent of:
2813+
//
2814+
// for item in iter.into_iter() {
2815+
// self.push_back(item);
2816+
// }
2817+
let mut iter = iter.into_iter();
2818+
while let Some(element) = iter.next() {
2819+
if self.len() == self.capacity() {
2820+
let (lower, _) = iter.size_hint();
2821+
self.reserve(lower.saturating_add(1));
2822+
}
2823+
2824+
let head = self.head;
2825+
self.head = self.wrap_add(self.head, 1);
2826+
unsafe { self.buffer_write(head, element); }
2827+
}
28132828
}
28142829
}
28152830

0 commit comments

Comments
 (0)