diff --git a/src/types/list.rs b/src/types/list.rs index 14e9f63b68d..3acbf162c28 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -83,9 +83,22 @@ impl PyList { } } + /// Takes a slice of the list from indices `low` to `high` and returns it as a new list. + /// + /// Out-of-range indices are clipped to `self.len()`. + pub fn slice(&self, low: usize, high: usize) -> &PyList { + unsafe { + self.py().from_owned_ptr(ffi::PyList_GetSlice( + self.as_ptr(), + low as isize, + high as isize, + )) + } + } + /// Sets the item at the specified index. /// - /// Panics if the index is out of range. + /// Raises `IndexError` if the index is out of range. pub fn set_item(&self, index: isize, item: I) -> PyResult<()> where I: ToPyObject, @@ -110,13 +123,16 @@ impl PyList { /// Inserts an item at the specified index. /// - /// Panics if the index is out of range. - pub fn insert(&self, index: isize, item: I) -> PyResult<()> + /// If `index >= self.len()`, inserts at the end. + pub fn insert(&self, index: usize, item: I) -> PyResult<()> where I: ToBorrowedObject, { item.with_borrowed_ptr(self.py(), |item| unsafe { - err::error_on_minusone(self.py(), ffi::PyList_Insert(self.as_ptr(), index, item)) + err::error_on_minusone( + self.py(), + ffi::PyList_Insert(self.as_ptr(), index as isize, item), + ) }) } @@ -251,14 +267,27 @@ mod tests { }); } + #[test] + fn test_slice() { + Python::with_gil(|py| { + let list = PyList::new(py, &[2, 3, 5, 7]); + let slice = list.slice(1, 3); + assert_eq!(2, slice.len()); + let slice = list.slice(1, 7); + assert_eq!(3, slice.len()); + }); + } + #[test] fn test_set_item() { Python::with_gil(|py| { let list = PyList::new(py, &[2, 3, 5, 7]); let val = 42i32.to_object(py); + let val2 = 42i32.to_object(py); assert_eq!(2, list.get_item(0).extract::().unwrap()); list.set_item(0, val).unwrap(); assert_eq!(42, list.get_item(0).extract::().unwrap()); + assert!(list.set_item(10, val2).is_err()); }); } @@ -285,12 +314,15 @@ mod tests { Python::with_gil(|py| { let list = PyList::new(py, &[2, 3, 5, 7]); let val = 42i32.to_object(py); + let val2 = 43i32.to_object(py); assert_eq!(4, list.len()); assert_eq!(2, list.get_item(0).extract::().unwrap()); list.insert(0, val).unwrap(); - assert_eq!(5, list.len()); + list.insert(1000, val2).unwrap(); + assert_eq!(6, list.len()); assert_eq!(42, list.get_item(0).extract::().unwrap()); assert_eq!(2, list.get_item(1).extract::().unwrap()); + assert_eq!(43, list.get_item(5).extract::().unwrap()); }); }