mirror of
https://github.com/rust-lang/rust.git
synced 2025-06-06 04:08:40 +00:00
std: Add Vec::from_iter comment
Requested by Niko in #22200 (and is good to have anyway)
This commit is contained in:
parent
f1bb6c2f46
commit
95a28c9bbd
@ -1383,7 +1383,7 @@ impl<T> ops::DerefMut for Vec<T> {
|
|||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
impl<T> FromIterator<T> for Vec<T> {
|
impl<T> FromIterator<T> for Vec<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_iter<I:Iterator<Item=T>>(iterator: I) -> Vec<T> {
|
fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> {
|
||||||
let (lower, _) = iterator.size_hint();
|
let (lower, _) = iterator.size_hint();
|
||||||
let mut vector = Vec::with_capacity(lower);
|
let mut vector = Vec::with_capacity(lower);
|
||||||
|
|
||||||
@ -1393,13 +1393,20 @@ impl<T> FromIterator<T> for Vec<T> {
|
|||||||
// vector.push(item);
|
// vector.push(item);
|
||||||
// }
|
// }
|
||||||
//
|
//
|
||||||
// This equivalent crucially runs the iterator precisely once. The
|
// This equivalent crucially runs the iterator precisely once. Below we
|
||||||
// optimization below (eliding bound/growth checks) means that we
|
// actually in theory run the iterator twice (one without bounds checks
|
||||||
// actually run the iterator twice. To ensure the "moral equivalent" we
|
// and one with). To achieve the "moral equivalent", we use the `if`
|
||||||
// do a `fuse()` operation to ensure that the iterator continues to
|
// statement below to break out early.
|
||||||
// return `None` after seeing the first `None`.
|
//
|
||||||
let mut i = iterator.fuse();
|
// If the first loop has terminated, then we have one of two conditions.
|
||||||
for element in i.by_ref().take(vector.capacity()) {
|
//
|
||||||
|
// 1. The underlying iterator returned `None`. In this case we are
|
||||||
|
// guaranteed that less than `vector.capacity()` elements have been
|
||||||
|
// returned, so we break out early.
|
||||||
|
// 2. The underlying iterator yielded `vector.capacity()` elements and
|
||||||
|
// has not yielded `None` yet. In this case we run the iterator to
|
||||||
|
// its end below.
|
||||||
|
for element in iterator.by_ref().take(vector.capacity()) {
|
||||||
let len = vector.len();
|
let len = vector.len();
|
||||||
unsafe {
|
unsafe {
|
||||||
ptr::write(vector.get_unchecked_mut(len), element);
|
ptr::write(vector.get_unchecked_mut(len), element);
|
||||||
@ -1407,8 +1414,10 @@ impl<T> FromIterator<T> for Vec<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for element in i {
|
if vector.len() == vector.capacity() {
|
||||||
vector.push(element)
|
for element in iterator {
|
||||||
|
vector.push(element);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
vector
|
vector
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user