Skip to content

Commit 055e577

Browse files
committed
Fix panic on out of bounds negative index (addresses RustPython#295)
Also an out of bounds index now raises an IndexError rather than a ValueError
1 parent 0f87d15 commit 055e577

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

vm/src/obj/objsequence.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@ pub trait PySliceableSequence {
1313
fn len(&self) -> usize;
1414
fn get_pos(&self, p: i32) -> usize {
1515
if p < 0 {
16-
self.len() - ((-p) as usize)
16+
if -p as usize > self.len() {
17+
// return something that is out of bounds so get_item raises an IndexError
18+
self.len() + 1
19+
} else {
20+
self.len() - ((-p) as usize)
21+
}
1722
} else if p as usize > self.len() {
1823
// This is for the slicing case where the end element is greater than the length of the
1924
// sequence
@@ -78,8 +83,8 @@ pub fn get_item(
7883
let obj = elements[pos_index].clone();
7984
Ok(obj)
8085
} else {
81-
let value_error = vm.context().exceptions.value_error.clone();
82-
Err(vm.new_exception(value_error, "Index out of bounds!".to_string()))
86+
let index_error = vm.context().exceptions.index_error.clone();
87+
Err(vm.new_exception(index_error, "Index out of bounds!".to_string()))
8388
}
8489
}
8590
PyObjectPayload::Slice {

0 commit comments

Comments
 (0)