alloc/vec/spec_from_iter_nested.rs
1use core::iter::TrustedLen;
2use core::{cmp, ptr};
3
4use super::{SpecExtend, Vec};
5use crate::raw_vec::RawVec;
6
7/// Another specialization trait for Vec::from_iter
8/// necessary to manually prioritize overlapping specializations
9/// see [`SpecFromIter`](super::SpecFromIter) for details.
10pub(super) trait SpecFromIterNested<T, I> {
11 fn from_iter(iter: I) -> Self;
12}
13
14impl<T, I> SpecFromIterNested<T, I> for Vec<T>
15where
16 I: Iterator<Item = T>,
17{
18 default fn from_iter(mut iterator: I) -> Self {
19 // Unroll the first iteration, as the vector is going to be
20 // expanded on this iteration in every case when the iterable is not
21 // empty, but the loop in extend_desugared() is not going to see the
22 // vector being full in the few subsequent loop iterations.
23 // So we get better branch prediction.
24 let mut vector = match iterator.next() {
25 None => return Vec::new(),
26 Some(element) => {
27 let (lower, _) = iterator.size_hint();
28 let initial_capacity =
29 cmp::max(RawVec::<T>::MIN_NON_ZERO_CAP, lower.saturating_add(1));
30 let mut vector = Vec::with_capacity(initial_capacity);
31 unsafe {
32 // SAFETY: We requested capacity at least 1
33 ptr::write(vector.as_mut_ptr(), element);
34 vector.set_len(1);
35 }
36 vector
37 }
38 };
39 // must delegate to spec_extend() since extend() itself delegates
40 // to spec_from for empty Vecs
41 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
42 vector
43 }
44}
45
46impl<T, I> SpecFromIterNested<T, I> for Vec<T>
47where
48 I: TrustedLen<Item = T>,
49{
50 fn from_iter(iterator: I) -> Self {
51 let mut vector = match iterator.size_hint() {
52 (_, Some(upper)) => Vec::with_capacity(upper),
53 // TrustedLen contract guarantees that `size_hint() == (_, None)` means that there
54 // are more than `usize::MAX` elements.
55 // Since the previous branch would eagerly panic if the capacity is too large
56 // (via `with_capacity`) we do the same here.
57 _ => panic!("capacity overflow"),
58 };
59 // reuse extend specialization for TrustedLen
60 vector.spec_extend(iterator);
61 vector
62 }
63}