-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathpython.rs
More file actions
59 lines (52 loc) · 1.79 KB
/
python.rs
File metadata and controls
59 lines (52 loc) · 1.79 KB
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::types::PyIterator;
use vortex::array::ArrayRef;
use vortex::array::iter::ArrayIterator;
use vortex::dtype::DType;
use vortex::error::VortexResult;
use vortex::error::vortex_err;
use crate::arrays::PyArrayRef;
/// Wrap a Python iterator over arrays as an [`ArrayIterator`].
pub struct PythonArrayIterator {
dtype: DType,
iter: Py<PyIterator>,
}
impl PythonArrayIterator {
pub fn try_new(dtype: DType, iter: Py<PyIterator>) -> PyResult<Self> {
Ok(PythonArrayIterator { dtype, iter })
}
}
impl ArrayIterator for PythonArrayIterator {
fn dtype(&self) -> &DType {
&self.dtype
}
}
impl Iterator for PythonArrayIterator {
type Item = VortexResult<ArrayRef>;
fn next(&mut self) -> Option<Self::Item> {
// Check for any signals on this chunk.
Python::attach(|py| {
let mut iter = self.iter.clone_ref(py).into_bound(py);
iter.next().map(|array| {
array
.and_then(|array| array.extract::<PyArrayRef>())
.map(|pyarray| pyarray.into_inner())
.and_then(|array| {
if array.dtype() != &self.dtype {
Err(PyTypeError::new_err(format!(
"ArrayIterator dtype mismatch. Expected {:?}, got {:?}",
&self.dtype,
array.dtype()
)))
} else {
Ok(array)
}
})
.map_err(|pyerr| vortex_err!("{}", pyerr))
})
})
}
}