risingwave_common/array/
iterator.rs1use std::iter::TrustedLen;
16
17use super::Array;
18
19pub struct ArrayIterator<'a, A: Array> {
20 data: &'a A,
21 pos: usize,
22}
23
24impl<'a, A: Array> ArrayIterator<'a, A> {
25 pub fn new(data: &'a A) -> Self {
26 Self { data, pos: 0 }
27 }
28}
29
30impl<'a, A: Array> Iterator for ArrayIterator<'a, A> {
31 type Item = Option<A::RefItem<'a>>;
32
33 fn next(&mut self) -> Option<Self::Item> {
34 if self.pos >= self.data.len() {
35 None
36 } else {
37 let item = unsafe { self.data.value_at_unchecked(self.pos) };
39 self.pos += 1;
40 Some(item)
41 }
42 }
43
44 fn size_hint(&self) -> (usize, Option<usize>) {
45 let size = self.data.len() - self.pos;
46 (size, Some(size))
47 }
48}
49
50impl<A: Array> ExactSizeIterator for ArrayIterator<'_, A> {}
51unsafe impl<A: Array> TrustedLen for ArrayIterator<'_, A> {}
52
53#[cfg(test)]
54mod tests {
55 use paste::paste;
56
57 use super::*;
58 use crate::array::{ArrayBuilder, ArrayImpl};
59 use crate::for_all_variants;
60
61 macro_rules! test_trusted_len {
62 ($( { $data_type:ident, $variant_name:ident, $suffix_name:ident, $scalar:ty, $scalar_ref:ty, $array:ty, $builder:ty } ),*) => {
63 $(
64 paste! {
65 #[test]
66 fn [<test_trusted_len_for_ $suffix_name _array>]() {
67 let mut builder = $builder::new(5);
68 for _ in 0..5 {
69 builder.append_null();
70 }
71 let array = builder.finish();
72 let mut iter = array.iter();
73
74 assert_eq!(iter.size_hint(), (5, Some(5))); iter.next();
75 assert_eq!(iter.size_hint(), (4, Some(4))); iter.next();
76 assert_eq!(iter.size_hint(), (3, Some(3))); iter.nth(0);
77 assert_eq!(iter.size_hint(), (2, Some(2))); iter.nth(1);
78 assert_eq!(iter.size_hint(), (0, Some(0)));
79
80 let array_impl = ArrayImpl::from(array);
81 let mut iter = array_impl.iter();
82
83 assert_eq!(iter.size_hint(), (5, Some(5))); iter.next();
84 assert_eq!(iter.size_hint(), (4, Some(4))); iter.next();
85 assert_eq!(iter.size_hint(), (3, Some(3))); iter.nth(0);
86 assert_eq!(iter.size_hint(), (2, Some(2))); iter.nth(1);
87 assert_eq!(iter.size_hint(), (0, Some(0)));
88 }
89 }
90 )*
91 };
92 }
93
94 for_all_variants! { test_trusted_len }
95}