From 055e5774241c0f3a4ed431f741e2e5413f8a9adf Mon Sep 17 00:00:00 2001 From: Homer McMillan Date: Sun, 3 Feb 2019 16:38:04 -0500 Subject: [PATCH] Fix panic on out of bounds negative index (addresses #295) Also an out of bounds index now raises an IndexError rather than a ValueError --- vm/src/obj/objsequence.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/vm/src/obj/objsequence.rs b/vm/src/obj/objsequence.rs index 3bb6933fc..65bff64a6 100644 --- a/vm/src/obj/objsequence.rs +++ b/vm/src/obj/objsequence.rs @@ -13,7 +13,12 @@ pub trait PySliceableSequence { fn len(&self) -> usize; fn get_pos(&self, p: i32) -> usize { if p < 0 { - self.len() - ((-p) as usize) + if -p as usize > self.len() { + // return something that is out of bounds so get_item raises an IndexError + self.len() + 1 + } else { + self.len() - ((-p) as usize) + } } else if p as usize > self.len() { // This is for the slicing case where the end element is greater than the length of the // sequence @@ -78,8 +83,8 @@ pub fn get_item( let obj = elements[pos_index].clone(); Ok(obj) } else { - let value_error = vm.context().exceptions.value_error.clone(); - Err(vm.new_exception(value_error, "Index out of bounds!".to_string())) + let index_error = vm.context().exceptions.index_error.clone(); + Err(vm.new_exception(index_error, "Index out of bounds!".to_string())) } } PyObjectPayload::Slice {