use crate::conversion::ToPyObject;
use crate::err::{PyErr, PyResult};
use crate::ffi;
use crate::objects::PyObject;
use crate::python::{Python, PythonObject, PythonObjectDowncastError, ToPythonPointer};
pub struct PyIterator<'p> {
py: Python<'p>,
iter: PyObject,
}
impl<'p> PyIterator<'p> {
pub fn from_object(
py: Python<'p>,
obj: PyObject,
) -> Result<PyIterator<'p>, PythonObjectDowncastError<'p>> {
if unsafe { ffi::PyIter_Check(obj.as_ptr()) != 0 } {
Ok(PyIterator { py, iter: obj })
} else {
Err(PythonObjectDowncastError::new(
py,
"PyIterator",
obj.get_type(py),
))
}
}
#[inline]
pub fn as_object(&self) -> &PyObject {
&self.iter
}
#[inline]
pub fn into_object(self) -> PyObject {
self.iter
}
}
impl<'p> Iterator for PyIterator<'p> {
type Item = PyResult<PyObject>;
fn next(&mut self) -> Option<PyResult<PyObject>> {
let py = self.py;
match unsafe { PyObject::from_owned_ptr_opt(py, ffi::PyIter_Next(self.iter.as_ptr())) } {
Some(obj) => Some(Ok(obj)),
None => {
if PyErr::occurred(py) {
Some(Err(PyErr::fetch(py)))
} else {
None
}
}
}
}
}
#[cfg(test)]
mod tests {
use crate::conversion::ToPyObject;
use crate::objectprotocol::ObjectProtocol;
use crate::python::{Python, PythonObject};
#[test]
fn vec_iter() {
let gil_guard = Python::acquire_gil();
let py = gil_guard.python();
let obj = vec![10, 20].to_py_object(py).into_object();
let mut it = obj.iter(py).unwrap();
assert_eq!(10, it.next().unwrap().unwrap().extract(py).unwrap());
assert_eq!(20, it.next().unwrap().unwrap().extract(py).unwrap());
assert!(it.next().is_none());
}
}