Skip to content

Commit 1792e83

Browse files
authored
Merge pull request #1922 from dtolnay/outofbounds
Improve panic message on Punctuated index out of bounds
2 parents 9c3101a + 532e4af commit 1792e83

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

src/punctuated.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1072,7 +1072,7 @@ impl<T, P> Index<usize> for Punctuated<T, P> {
10721072
type Output = T;
10731073

10741074
fn index(&self, index: usize) -> &Self::Output {
1075-
if index == self.len() - 1 {
1075+
if index.checked_add(1) == Some(self.len()) {
10761076
match &self.last {
10771077
Some(t) => t,
10781078
None => &self.inner[index].0,
@@ -1085,7 +1085,7 @@ impl<T, P> Index<usize> for Punctuated<T, P> {
10851085

10861086
impl<T, P> IndexMut<usize> for Punctuated<T, P> {
10871087
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1088-
if index == self.len() - 1 {
1088+
if index.checked_add(1) == Some(self.len()) {
10891089
match &mut self.last {
10901090
Some(t) => t,
10911091
None => &mut self.inner[index].0,

tests/test_punctuated.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,10 @@ fn may_dangle() {
8383
}
8484
}
8585
}
86+
87+
#[test]
88+
#[should_panic = "index out of bounds: the len is 0 but the index is 0"]
89+
fn index_out_of_bounds() {
90+
let p = Punctuated::<syn::Ident, Token![,]>::new();
91+
let _ = p[0].clone();
92+
}

0 commit comments

Comments
 (0)