Skip to content

Commit

Permalink
Auto merge of rust-lang#92138 - AngelicosPhosphoros:try_smarter_vec_f…
Browse files Browse the repository at this point in the history
…rom_iter_48994_2, r=Mark-Simulacrum

Improve capacity estimation in Vec::from_iter

Iterates on the attempt made in rust-lang#53086.

Closes rust-lang#48994
  • Loading branch information
bors committed Jan 20, 2022
2 parents 237949b + ea570c6 commit 74fbbef
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
2 changes: 1 addition & 1 deletion library/alloc/src/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl<T, A: Allocator> RawVec<T, A> {
// to round up a request of less than 8 bytes to at least 8 bytes.
// - 4 if elements are moderate-sized (<= 1 KiB).
// - 1 otherwise, to avoid wasting too much space for very short Vecs.
const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
pub(crate) const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
8
} else if mem::size_of::<T>() <= 1024 {
4
Expand Down
10 changes: 8 additions & 2 deletions library/alloc/src/vec/spec_from_iter_nested.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use core::cmp;
use core::iter::TrustedLen;
use core::ptr::{self};
use core::ptr;

use crate::raw_vec::RawVec;

use super::{SpecExtend, Vec};

Expand All @@ -24,8 +27,11 @@ where
None => return Vec::new(),
Some(element) => {
let (lower, _) = iterator.size_hint();
let mut vector = Vec::with_capacity(lower.saturating_add(1));
let initial_capacity =
cmp::max(RawVec::<T>::MIN_NON_ZERO_CAP, lower.saturating_add(1));
let mut vector = Vec::with_capacity(initial_capacity);
unsafe {
// SAFETY: We requested capacity at least 1
ptr::write(vector.as_mut_ptr(), element);
vector.set_len(1);
}
Expand Down

0 comments on commit 74fbbef

Please sign in to comment.