Skip to content

Commit

Permalink
Auto merge of #65749 - Centril:insurance-policy, r=<try>
Browse files Browse the repository at this point in the history
Insurance policy in case `iter.size_hint()` lies.

Follow up to https://github.com/rust-lang/rust/pull/64949/files#r334235076.
(If the perf impact is bad we can use `debug_assert!` instead.)

The good news is that the UI tests pass locally so `iter.size_hint()` seems to be honest *thus far*.
On the other hand, with the status quo we do not have an insurance policy should that change in some case. This is problematic because a) this could possibly make some program be accepted which shouldn't, b) the compiler itself could have memory unsafety if the correctness of the iterator is assumed in `unsafe { ... }` code (even though the blame lies with the `unsafe { ... }` block in question.)

r? @RalfJung
cc @nnethercote
  • Loading branch information
bors committed Oct 25, 2019
2 parents 10a52c2 + c85bfc5 commit 2beb6a3
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions src/librustc/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2866,25 +2866,27 @@ impl<T, R, E> InternIteratorElement<T, R> for Result<T, E> {
-> Self::Output {
// This code is hot enough that it's worth specializing for the most
// common length lists, to avoid the overhead of `SmallVec` creation.
// The match arms are in order of frequency. The 1, 2, and 0 cases are
// typically hit in ~95% of cases. We assume that if the upper and
// lower bounds from `size_hint` agree they are correct.
Ok(match iter.size_hint() {
(1, Some(1)) => {
f(&[iter.next().unwrap()?])
}
(2, Some(2)) => {
let t0 = iter.next().unwrap()?;
let t1 = iter.next().unwrap()?;
f(&[t0, t1])
}
(0, Some(0)) => {
f(&[])
}
_ => {
f(&iter.collect::<Result<SmallVec<[_; 8]>, _>>()?)
}
})
// In terms of frequency, lengths 1, 2, and 0 are typically hit in ~95% of cases.
let e0 = match iter.next() {
Some(x) => x?,
None => return Ok(f(&[])),
};
let e1 = match iter.next() {
None => return Ok(f(&[e0])),
Some(x) => x?,
};
let e2 = match iter.next() {
None => return Ok(f(&[e0, e1])),
Some(x) => x?,
};
let mut vec: SmallVec<[_; 8]> = SmallVec::with_capacity(3 + iter.size_hint().0);
vec.push(e0);
vec.push(e1);
vec.push(e2);
for result in iter {
vec.push(result?);
}
Ok(f(&vec))
}
}

Expand Down

0 comments on commit 2beb6a3

Please sign in to comment.