Skip to content

Commit 2692d89

Browse files
committed
fix limited API and PyPy support
1 parent 7d3fad0 commit 2692d89

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

src/types/list.rs

+50-2
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,7 @@ impl ListIterImpl {
497497
#[inline]
498498
/// Safety: the list should be locked with a critical section on the free-threaded build
499499
/// and otherwise not shared between threads when the GIL is released.
500+
#[cfg(all(not(Py_LIMITED_API), not(PyPy)))]
500501
unsafe fn next_unchecked<'py>(
501502
&mut self,
502503
list: &Bound<'py, PyList>,
@@ -517,7 +518,28 @@ impl ListIterImpl {
517518
}
518519
}
519520

521+
#[cfg(any(Py_LIMITED_API, PyPy))]
522+
fn next<'py>(&mut self, list: &Bound<'py, PyList>) -> Option<Bound<'py, PyAny>> {
523+
match self {
524+
Self::ListIter { index, length, .. } => {
525+
let length = (*length).min(list.len());
526+
let my_index = *index;
527+
528+
if *index < length {
529+
let item = list.get_item(my_index).expect("get-item failed");
530+
*index += 1;
531+
Some(item)
532+
} else {
533+
None
534+
}
535+
}
536+
}
537+
}
538+
539+
/// Safety: the list should be locked with a critical section on the free-threaded build
540+
/// and otherwise not shared between threads when the GIL is released.
520541
#[inline]
542+
#[cfg(all(not(Py_LIMITED_API), not(PyPy)))]
521543
unsafe fn next_back_unchecked<'py>(
522544
&mut self,
523545
list: &Bound<'py, PyList>,
@@ -537,6 +559,24 @@ impl ListIterImpl {
537559
}
538560
}
539561

562+
#[inline]
563+
#[cfg(any(Py_LIMITED_API, PyPy))]
564+
fn next_back<'py>(&mut self, list: &Bound<'py, PyList>) -> Option<Bound<'py, PyAny>> {
565+
match self {
566+
Self::ListIter { index, length, .. } => {
567+
let current_length = (*length).min(list.len());
568+
569+
if *index < current_length {
570+
let item = list.get_item(current_length - 1).expect("get-item failed");
571+
*length = current_length - 1;
572+
Some(item)
573+
} else {
574+
None
575+
}
576+
}
577+
}
578+
}
579+
540580
#[inline]
541581
fn len(&self) -> usize {
542582
match self {
@@ -578,7 +618,11 @@ impl<'py> Iterator for BoundListIterator<'py> {
578618
inner.next_unchecked(&self.list)
579619
})
580620
}
581-
#[cfg(not(Py_GIL_DISABLED))]
621+
#[cfg(any(Py_LIMITED_API, PyPy))]
622+
{
623+
self.inner.next(&self.list)
624+
}
625+
#[cfg(all(not(Py_GIL_DISABLED), not(Py_LIMITED_API), not(PyPy)))]
582626
{
583627
unsafe { self.inner.next_unchecked(&self.list) }
584628
}
@@ -704,7 +748,11 @@ impl DoubleEndedIterator for BoundListIterator<'_> {
704748
inner.next_back_unchecked(&self.list)
705749
})
706750
}
707-
#[cfg(not(Py_GIL_DISABLED))]
751+
#[cfg(any(Py_LIMITED_API, PyPy))]
752+
{
753+
self.inner.next_back(&self.list)
754+
}
755+
#[cfg(all(not(Py_GIL_DISABLED), not(Py_LIMITED_API), not(PyPy)))]
708756
{
709757
unsafe { self.inner.next_back_unchecked(&self.list) }
710758
}

0 commit comments

Comments
 (0)