1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use python::{Python, PythonObject, ToPythonPointer, PythonObjectDowncastError};
use conversion::ToPyObject;
use objects::PyObject;
use err::{PyErr, PyResult};
use ffi;
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: py, iter: obj })
} else {
Err(PythonObjectDowncastError(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 python::{Python, PythonObject};
use conversion::ToPyObject;
use objectprotocol::ObjectProtocol;
#[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());
}
}