polars_arrow/array/map/
iterator.rs

1use super::MapArray;
2use crate::array::Array;
3use crate::bitmap::utils::{BitmapIter, ZipValidity};
4use crate::trusted_len::TrustedLen;
5
6/// Iterator of values of an [`ListArray`].
7#[derive(Clone, Debug)]
8pub struct MapValuesIter<'a> {
9    array: &'a MapArray,
10    index: usize,
11    end: usize,
12}
13
14impl<'a> MapValuesIter<'a> {
15    #[inline]
16    pub fn new(array: &'a MapArray) -> Self {
17        Self {
18            array,
19            index: 0,
20            end: array.len(),
21        }
22    }
23}
24
25impl Iterator for MapValuesIter<'_> {
26    type Item = Box<dyn Array>;
27
28    #[inline]
29    fn next(&mut self) -> Option<Self::Item> {
30        if self.index == self.end {
31            return None;
32        }
33        let old = self.index;
34        self.index += 1;
35        // SAFETY:
36        // self.end is maximized by the length of the array
37        Some(unsafe { self.array.value_unchecked(old) })
38    }
39
40    #[inline]
41    fn size_hint(&self) -> (usize, Option<usize>) {
42        (self.end - self.index, Some(self.end - self.index))
43    }
44}
45
46unsafe impl TrustedLen for MapValuesIter<'_> {}
47
48impl DoubleEndedIterator for MapValuesIter<'_> {
49    #[inline]
50    fn next_back(&mut self) -> Option<Self::Item> {
51        if self.index == self.end {
52            None
53        } else {
54            self.end -= 1;
55            // SAFETY:
56            // self.end is maximized by the length of the array
57            Some(unsafe { self.array.value_unchecked(self.end) })
58        }
59    }
60}
61
62impl<'a> IntoIterator for &'a MapArray {
63    type Item = Option<Box<dyn Array>>;
64    type IntoIter = ZipValidity<Box<dyn Array>, MapValuesIter<'a>, BitmapIter<'a>>;
65
66    fn into_iter(self) -> Self::IntoIter {
67        self.iter()
68    }
69}
70
71impl<'a> MapArray {
72    /// Returns an iterator of `Option<Box<dyn Array>>`
73    pub fn iter(&'a self) -> ZipValidity<Box<dyn Array>, MapValuesIter<'a>, BitmapIter<'a>> {
74        ZipValidity::new_with_validity(MapValuesIter::new(self), self.validity())
75    }
76
77    /// Returns an iterator of `Box<dyn Array>`
78    pub fn values_iter(&'a self) -> MapValuesIter<'a> {
79        MapValuesIter::new(self)
80    }
81}