cpython/objects/iterator.rs
1// Copyright (c) 2015 Daniel Grunwald
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy of this
4// software and associated documentation files (the "Software"), to deal in the Software
5// without restriction, including without limitation the rights to use, copy, modify, merge,
6// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
7// to whom the Software is furnished to do so, subject to the following conditions:
8//
9// The above copyright notice and this permission notice shall be included in all copies or
10// substantial portions of the Software.
11//
12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
17// DEALINGS IN THE SOFTWARE.
18
19use crate::conversion::ToPyObject;
20use crate::err::{PyErr, PyResult};
21use crate::ffi;
22use crate::objects::PyObject;
23use crate::python::{Python, PythonObject, PythonObjectDowncastError, ToPythonPointer};
24
25/// A python iterator object.
26///
27/// Unlike other python objects, this class includes a `Python<'p>` token
28/// so that PyIterator can implement the rust `Iterator` trait.
29pub struct PyIterator<'p> {
30 py: Python<'p>,
31 iter: PyObject,
32}
33
34impl<'p> PyIterator<'p> {
35 /// Constructs a PyIterator from a Python iterator object.
36 pub fn from_object(
37 py: Python<'p>,
38 obj: PyObject,
39 ) -> Result<PyIterator<'p>, PythonObjectDowncastError<'p>> {
40 if unsafe { ffi::PyIter_Check(obj.as_ptr()) != 0 } {
41 Ok(PyIterator { py, iter: obj })
42 } else {
43 Err(PythonObjectDowncastError::new(
44 py,
45 "PyIterator",
46 obj.get_type(py),
47 ))
48 }
49 }
50
51 /// Gets the Python iterator object.
52 #[inline]
53 pub fn as_object(&self) -> &PyObject {
54 &self.iter
55 }
56
57 /// Gets the Python iterator object.
58 #[inline]
59 pub fn into_object(self) -> PyObject {
60 self.iter
61 }
62}
63
64impl<'p> Iterator for PyIterator<'p> {
65 type Item = PyResult<PyObject>;
66
67 /// Retrieves the next item from an iterator.
68 /// Returns `None` when the iterator is exhausted.
69 /// If an exception occurs, returns `Some(Err(..))`.
70 /// Further next() calls after an exception occurs are likely
71 /// to repeatedly result in the same exception.
72 fn next(&mut self) -> Option<PyResult<PyObject>> {
73 let py = self.py;
74 match unsafe { PyObject::from_owned_ptr_opt(py, ffi::PyIter_Next(self.iter.as_ptr())) } {
75 Some(obj) => Some(Ok(obj)),
76 None => {
77 if PyErr::occurred(py) {
78 Some(Err(PyErr::fetch(py)))
79 } else {
80 None
81 }
82 }
83 }
84 }
85}
86
87#[cfg(test)]
88mod tests {
89 use crate::conversion::ToPyObject;
90 use crate::objectprotocol::ObjectProtocol;
91 use crate::python::{Python, PythonObject};
92
93 #[test]
94 fn vec_iter() {
95 let gil_guard = Python::acquire_gil();
96 let py = gil_guard.python();
97 let obj = vec![10, 20].to_py_object(py).into_object();
98 let mut it = obj.iter(py).unwrap();
99 assert_eq!(10, it.next().unwrap().unwrap().extract(py).unwrap());
100 assert_eq!(20, it.next().unwrap().unwrap().extract(py).unwrap());
101 assert!(it.next().is_none());
102 }
103}