Skip to content

Commit 74fbbef

Browse files
committed
Auto merge of rust-lang#92138 - AngelicosPhosphoros:try_smarter_vec_from_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
2 parents 237949b + ea570c6 commit 74fbbef

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

library/alloc/src/raw_vec.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl<T, A: Allocator> RawVec<T, A> {
108108
// to round up a request of less than 8 bytes to at least 8 bytes.
109109
// - 4 if elements are moderate-sized (<= 1 KiB).
110110
// - 1 otherwise, to avoid wasting too much space for very short Vecs.
111-
const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
111+
pub(crate) const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
112112
8
113113
} else if mem::size_of::<T>() <= 1024 {
114114
4

library/alloc/src/vec/spec_from_iter_nested.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
use core::cmp;
12
use core::iter::TrustedLen;
2-
use core::ptr::{self};
3+
use core::ptr;
4+
5+
use crate::raw_vec::RawVec;
36

47
use super::{SpecExtend, Vec};
58

@@ -24,8 +27,11 @@ where
2427
None => return Vec::new(),
2528
Some(element) => {
2629
let (lower, _) = iterator.size_hint();
27-
let mut vector = Vec::with_capacity(lower.saturating_add(1));
30+
let initial_capacity =
31+
cmp::max(RawVec::<T>::MIN_NON_ZERO_CAP, lower.saturating_add(1));
32+
let mut vector = Vec::with_capacity(initial_capacity);
2833
unsafe {
34+
// SAFETY: We requested capacity at least 1
2935
ptr::write(vector.as_mut_ptr(), element);
3036
vector.set_len(1);
3137
}

0 commit comments

Comments
 (0)