Commit 6da4df9
committed
Make the semantics of Vec::truncate(N) consistent with slices.
This commit simplifies the implementation of `Vec::truncate(N)` and
makes its semantics identical to dropping the `[vec.len() - N..]`
sub-slice tail of the vector, which is the same behavior as dropping a
vector containing the same sub-slice.
This changes two unspecified aspects of `Vec::truncate` behavior:
* the drop order, from back-to-front to front-to-back,
* the behavior of `Vec::truncate` on panics: if dropping one element of
the tail panics, currently, `Vec::truncate` panics, but with this PR all other
elements are still dropped, and if dropping a second element of the tail
panics, with this PR, the program aborts.
Programs can trivially observe both changes. For example
([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7bef575b83b06e82b3e3529e4edbcac7)):
```rust
fn main() {
struct Bomb(usize);
impl Drop for Bomb {
fn drop(&mut self) {
panic!(format!("{}", self.0));
}
}
let mut v = vec![Bomb(0), Bomb(1)];
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
v.truncate(0);
}));
assert_eq!(v.len(), 1);
std::mem::forget(v);
}
```
panics printing `1` today and succeeds. With this change, it panics
printing `0` first (due to the drop order change), and then aborts
with a double-panic printing `1`, just like dropping the
`[Bomb(0), Bomb(1)]` slice does, or dropping
`vec![Bomb(0), Bomb(1)]` does.1 parent 572d3d9 commit 6da4df9
1 file changed
+12
-22
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
685 | 685 | | |
686 | 686 | | |
687 | 687 | | |
688 | | - | |
689 | | - | |
690 | | - | |
691 | | - | |
692 | | - | |
693 | | - | |
694 | | - | |
695 | | - | |
696 | | - | |
697 | | - | |
698 | | - | |
699 | | - | |
700 | | - | |
701 | | - | |
702 | | - | |
703 | | - | |
| 688 | + | |
| 689 | + | |
| 690 | + | |
| 691 | + | |
| 692 | + | |
| 693 | + | |
| 694 | + | |
| 695 | + | |
| 696 | + | |
| 697 | + | |
704 | 698 | | |
705 | | - | |
| 699 | + | |
706 | 700 | | |
| 701 | + | |
707 | 702 | | |
708 | 703 | | |
709 | 704 | | |
| |||
1590 | 1585 | | |
1591 | 1586 | | |
1592 | 1587 | | |
1593 | | - | |
1594 | | - | |
1595 | | - | |
1596 | | - | |
1597 | | - | |
1598 | 1588 | | |
1599 | 1589 | | |
1600 | 1590 | | |
| |||
0 commit comments