Skip to content

Commit 54b27f9

Browse files
authored
Rollup merge of rust-lang#80834 - bugadani:vecdeque, r=oli-obk
Remove unreachable panics from VecDeque::{front/back}[_mut] `VecDeque`'s `front`, `front_mut`, `back` and `back_mut` methods are implemented in terms of the index operator, which causes these functions to contain [unreachable panic calls](https://rust.godbolt.org/z/MTnq1o). This PR reimplements these methods in terms of `get[_mut]` instead.
2 parents 4204450 + a398106 commit 54b27f9

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

library/alloc/src/collections/vec_deque/mod.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -1292,7 +1292,7 @@ impl<T> VecDeque<T> {
12921292
/// ```
12931293
#[stable(feature = "rust1", since = "1.0.0")]
12941294
pub fn front(&self) -> Option<&T> {
1295-
if !self.is_empty() { Some(&self[0]) } else { None }
1295+
self.get(0)
12961296
}
12971297

12981298
/// Provides a mutable reference to the front element, or `None` if the
@@ -1316,7 +1316,7 @@ impl<T> VecDeque<T> {
13161316
/// ```
13171317
#[stable(feature = "rust1", since = "1.0.0")]
13181318
pub fn front_mut(&mut self) -> Option<&mut T> {
1319-
if !self.is_empty() { Some(&mut self[0]) } else { None }
1319+
self.get_mut(0)
13201320
}
13211321

13221322
/// Provides a reference to the back element, or `None` if the `VecDeque` is
@@ -1336,7 +1336,7 @@ impl<T> VecDeque<T> {
13361336
/// ```
13371337
#[stable(feature = "rust1", since = "1.0.0")]
13381338
pub fn back(&self) -> Option<&T> {
1339-
if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
1339+
self.get(self.len().wrapping_sub(1))
13401340
}
13411341

13421342
/// Provides a mutable reference to the back element, or `None` if the
@@ -1360,8 +1360,7 @@ impl<T> VecDeque<T> {
13601360
/// ```
13611361
#[stable(feature = "rust1", since = "1.0.0")]
13621362
pub fn back_mut(&mut self) -> Option<&mut T> {
1363-
let len = self.len();
1364-
if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
1363+
self.get_mut(self.len().wrapping_sub(1))
13651364
}
13661365

13671366
/// Removes the first element and returns it, or `None` if the `VecDeque` is

src/test/codegen/vecdeque_no_panic.rs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// This test checks that `VecDeque::front[_mut]()` and `VecDeque::back[_mut]()` can't panic.
2+
3+
// compile-flags: -O
4+
// min-llvm-version: 11.0.0
5+
6+
#![crate_type = "lib"]
7+
8+
use std::collections::VecDeque;
9+
10+
// CHECK-LABEL: @dont_panic
11+
#[no_mangle]
12+
pub fn dont_panic(v: &mut VecDeque<usize>) {
13+
// CHECK-NOT: expect
14+
// CHECK-NOT: panic
15+
v.front();
16+
v.front_mut();
17+
v.back();
18+
v.back_mut();
19+
}

0 commit comments

Comments
 (0)