Skip to content

alloc: consider the iterator size hint on every resize in extend_desugared #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: patch-2
Choose a base branch
from
Open
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
24 changes: 9 additions & 15 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3543,21 +3543,15 @@ impl<T, A: Allocator> Vec<T, A> {
// for item in iterator {
// self.push(item);
// }
let (lower, _) = iterator.size_hint();
let initial_len = self.len();
iterator.for_each(move |element| {
let len = self.len();
if len == self.capacity() {
self.reserve(lower.saturating_sub(len - initial_len).saturating_add(1));
}
unsafe {
ptr::write(self.as_mut_ptr().add(len), element);
// Since next() executes user code which can panic we have to bump the length
// after each step.
// NB can't overflow since we would have had to alloc the address space
self.set_len(len + 1);
}
});
while let Err(item) = iterator.try_for_each(|item| self.push_within_capacity(item)) {
// As long as there is enough space, we push the items directly into
// the vector. Once we need more space, look at the iterators size
// hint to get an estimate for how much space to reserve.
let (lower, _) = iterator.size_hint();
self.reserve(lower.saturating_add(1));
// SAFETY: we just reserved space for at least one item.
unsafe { self.push_within_capacity(item).unwrap_unchecked() };
}
}

// specific extend for `TrustedLen` iterators, called both by the specializations
Expand Down