Skip to content

Commit

Permalink
Accept usize index for PyList::insert.
Browse files Browse the repository at this point in the history
NB: the behavior on out-of-range indices hasn't changed;
it was merely wrongly documented before.
  • Loading branch information
birkenfeld committed Aug 17, 2021
1 parent 336e87e commit f4d4750
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/types/list.rs
Expand Up @@ -110,13 +110,16 @@ impl PyList {

/// Inserts an item at the specified index.
///
/// Panics if the index is out of range.
pub fn insert<I>(&self, index: isize, item: I) -> PyResult<()>
/// If `index >= self.len()`, inserts at the end.
pub fn insert<I>(&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),
)
})
}

Expand Down Expand Up @@ -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::<i32>().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::<i32>().unwrap());
assert_eq!(2, list.get_item(1).extract::<i32>().unwrap());
assert_eq!(43, list.get_item(5).extract::<i32>().unwrap());
});
}

Expand Down

0 comments on commit f4d4750

Please sign in to comment.