Skip to content

Commit a6514ac

Browse files
committed
Raise IndexError when int overflow in str.__getitem__
1 parent 11650e9 commit a6514ac

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

vm/src/obj/objstr.rs

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use unicode_xid::UnicodeXID;
1717
use super::objbytes::PyBytes;
1818
use super::objdict::PyDict;
1919
use super::objfloat;
20-
use super::objint::{self, PyInt};
20+
use super::objint::{self, PyInt, PyIntRef};
2121
use super::objiter;
2222
use super::objnone::PyNone;
2323
use super::objsequence::PySliceableSequence;
@@ -229,21 +229,26 @@ impl PyString {
229229
}
230230

231231
#[pymethod(name = "__getitem__")]
232-
fn getitem(&self, needle: Either<isize, PySliceRef>, vm: &VirtualMachine) -> PyResult {
232+
fn getitem(&self, needle: Either<PyIntRef, PySliceRef>, vm: &VirtualMachine) -> PyResult {
233233
match needle {
234-
Either::A(pos) => {
235-
let index: usize = if pos.is_negative() {
236-
(self.value.chars().count() as isize + pos) as usize
237-
} else {
238-
pos.abs() as usize
239-
};
234+
Either::A(pos) => match pos.as_bigint().to_isize() {
235+
Some(pos) => {
236+
let index: usize = if pos.is_negative() {
237+
(self.value.chars().count() as isize + pos) as usize
238+
} else {
239+
pos.abs() as usize
240+
};
240241

241-
if let Some(character) = self.value.chars().nth(index) {
242-
Ok(vm.new_str(character.to_string()))
243-
} else {
244-
Err(vm.new_index_error("string index out of range".to_string()))
242+
if let Some(character) = self.value.chars().nth(index) {
243+
Ok(vm.new_str(character.to_string()))
244+
} else {
245+
Err(vm.new_index_error("string index out of range".to_string()))
246+
}
245247
}
246-
}
248+
None => Err(
249+
vm.new_index_error("cannot fit 'int' into an index-sized integer".to_string())
250+
),
251+
},
247252
Either::B(slice) => {
248253
let string = self
249254
.value

0 commit comments

Comments
 (0)