Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@
#![feature(alloc_layout_extra)]
#![feature(try_trait)]
#![feature(associated_type_bounds)]
#![feature(extend_with_capacity)]

// Allow testing this library

Expand Down
15 changes: 14 additions & 1 deletion src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2048,6 +2048,11 @@ impl<T> Extend<T> for Vec<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
<Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
}

#[inline]
fn with_capacity(capacity: usize) -> Self {
Self::with_capacity(capacity)
}
}

// Specialization trait used for Vec::from_iter and Vec::extend
Expand Down Expand Up @@ -2097,7 +2102,7 @@ where
vector
}

default fn spec_extend(&mut self, iterator: I) {
default fn spec_extend(&mut self, mut iterator: I) {
// This is the case for a TrustedLen iterator.
let (low, high) = iterator.size_hint();
if let Some(high_value) = high {
Expand All @@ -2109,6 +2114,14 @@ where
);
}
if let Some(additional) = high {
if additional == 1 {
// work around inefficiencies in generic vec.extend(Some(x))
if let Some(x) = iterator.next() {
self.push(x);
}
return;
}

self.reserve(additional);
unsafe {
let mut ptr = self.as_mut_ptr().add(self.len());
Expand Down
6 changes: 6 additions & 0 deletions src/libcore/iter/traits/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,12 @@ pub trait Extend<A> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);

/// Creates this collection with a reserved capacity.
#[unstable(feature = "extend_with_capacity", issue = "none")]
fn with_capacity(_capacity: usize) -> Self where Self: Default {
Self::default()
}
}

#[stable(feature = "extend_for_unit", since = "1.28.0")]
Expand Down
5 changes: 3 additions & 2 deletions src/libcore/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2672,8 +2672,9 @@ pub trait Iterator {
}
}

let mut ts: FromA = Default::default();
let mut us: FromB = Default::default();
let cap = self.size_hint().0.saturating_add(1);
let mut ts: FromA = Extend::with_capacity(cap);
let mut us: FromB = Extend::with_capacity(cap);

self.for_each(extend(&mut ts, &mut us));

Expand Down