From f4d4750be299e2b62faf3eed2fc0a14740386615 Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Tue, 17 Aug 2021 08:11:51 +0200 Subject: [PATCH] Accept usize index for PyList::insert. NB: the behavior on out-of-range indices hasn't changed; it was merely wrongly documented before. --- src/types/list.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/types/list.rs b/src/types/list.rs index 14e9f63b68d..43c74221553 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -110,13 +110,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), + ) }) } @@ -285,12 +288,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()); }); }