Skip to content

Commit 532e4af

Browse files
committed
Improve panic message on Punctuated index out of bounds
1 parent 909c222 commit 532e4af

File tree

2 files changed

+3
-3
lines changed

2 files changed

+3
-3
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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ fn may_dangle() {
8585
}
8686

8787
#[test]
88-
#[should_panic = "attempt to subtract with overflow"]
88+
#[should_panic = "index out of bounds: the len is 0 but the index is 0"]
8989
fn index_out_of_bounds() {
9090
let p = Punctuated::<syn::Ident, Token![,]>::new();
9191
let _ = p[0].clone();

0 commit comments

Comments
 (0)