Skip to content

Commit

Permalink
fix limited API and PyPy support
Browse files Browse the repository at this point in the history
  • Loading branch information
ngoldbaum committed Dec 11, 2024
1 parent 7d3fad0 commit d1d1824
Showing 1 changed file with 50 additions and 2 deletions.
52 changes: 50 additions & 2 deletions src/types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,7 @@ impl ListIterImpl {
#[inline]
/// Safety: the list should be locked with a critical section on the free-threaded build
/// and otherwise not shared between threads when the GIL is released.
#[cfg(all(not(Py_LIMITED_API), not(PyPy)))]
unsafe fn next_unchecked<'py>(
&mut self,
list: &Bound<'py, PyList>,
Expand All @@ -517,7 +518,28 @@ impl ListIterImpl {
}
}

#[cfg(any(Py_LIMITED_API, PyPy))]
fn next<'py>(&mut self, list: &Bound<'py, PyList>) -> Option<Bound<'py, PyAny>> {
match self {
Self::ListIter { index, length, .. } => {
let length = (*length).min(list.len());
let my_index = *index;

if *index < length {
let item = list.get_item(my_index).expect("get-item failed");
*index += 1;
Some(item)
} else {
None
}
}
}
}

/// Safety: the list should be locked with a critical section on the free-threaded build
/// and otherwise not shared between threads when the GIL is released.
#[inline]
#[cfg(all(not(Py_LIMITED_API), not(PyPy)))]
unsafe fn next_back_unchecked<'py>(
&mut self,
list: &Bound<'py, PyList>,
Expand All @@ -537,6 +559,24 @@ impl ListIterImpl {
}
}

#[inline]
#[cfg(any(Py_LIMITED_API, PyPy))]
fn next_back<'py>(&mut self, list: &Bound<'py, PyList>) -> Option<Bound<'py, PyAny>> {
match self {
Self::ListIter { index, length, .. } => {
let current_length = (*length).min(list.len());

if *index < current_length {
let item = list.get_item(current_length - 1).expect("get-item failed");
*length = current_length - 1;
Some(item)
} else {
None
}
}
}
}

#[inline]
fn len(&self) -> usize {
match self {
Expand Down Expand Up @@ -578,7 +618,11 @@ impl<'py> Iterator for BoundListIterator<'py> {
inner.next_unchecked(&self.list)
})
}
#[cfg(not(Py_GIL_DISABLED))]
#[cfg(Py_LIMITED_API)]
{
self.inner.next(&self.list)
}
#[cfg(all(not(Py_GIL_DISABLED), not(Py_LIMITED_API)))]
{
unsafe { self.inner.next_unchecked(&self.list) }
}
Expand Down Expand Up @@ -704,7 +748,11 @@ impl DoubleEndedIterator for BoundListIterator<'_> {
inner.next_back_unchecked(&self.list)
})
}
#[cfg(not(Py_GIL_DISABLED))]
#[cfg(Py_LIMITED_API)]
{
self.inner.next_back(&self.list)
}
#[cfg(all(not(Py_GIL_DISABLED), not(Py_LIMITED_API)))]
{
unsafe { self.inner.next_back_unchecked(&self.list) }
}
Expand Down

0 comments on commit d1d1824

Please sign in to comment.