PyList: fix segfault on get_item with negative indices

See #1667.
This commit is contained in:
Georg Brandl 2021-06-06 10:19:30 +02:00
parent 6b681143cc
commit cb6dedbe62
1 changed files with 10 additions and 1 deletions

View File

@ -70,7 +70,7 @@ impl PyList {
///
/// Panics if the index is out of range.
pub fn get_item(&self, index: isize) -> &PyAny {
assert!((index.abs() as usize) < self.len());
assert!(index >= 0 && index < self.len() as isize);
unsafe {
#[cfg(not(Py_LIMITED_API))]
let ptr = ffi::PyList_GET_ITEM(self.as_ptr(), index as Py_ssize_t);
@ -237,6 +237,15 @@ mod test {
assert_eq!(7, list.get_item(3).extract::<i32>().unwrap());
}
#[test]
#[should_panic]
fn test_get_item_invalid() {
let gil = Python::acquire_gil();
let py = gil.python();
let list = PyList::new(py, [2, 3, 5, 7]);
list.get_item(-1);
}
#[test]
fn test_set_item() {
let gil = Python::acquire_gil();