1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
910//! Defines a "lending iterator" for [`Row`]
1112use std::fmt::Debug;
13use std::sync::Arc;
1415use crate::row::{Row, RowRef};
1617/// An iterator that can borrow from `self` and yield [`RowRef`]s.
18///
19/// This trait is a "lending iterator" for [`Row`]s, in other words, an iterator that borrows from
20/// self (e.g. an underlying memory buffer) to return a [`RowRef`]. The [`std::iter::Iterator`]
21/// trait does not currently support this pattern because there is no way to name the lifetime of
22/// the borrow on its associated `Item` type. Generic Associated Types (GATs) would allow this but
23/// so far no new trait has been introduced with this API.
24///
25/// There are a few open source crates that provide a trait:
26///
27/// * [`streaming_iterator`](https://docs.rs/streaming-iterator/latest/streaming_iterator/)
28/// * [`lending-iterator`](https://docs.rs/lending-iterator/latest/lending_iterator/)
29///
30/// Neither have an `IntoLendingIterator` trait that is useful for our interface, nor do they work
31/// well with trait objects.
32pub trait RowIterator: Debug {
33/// Returns the next [`RowRef`] advancing the iterator.
34fn next(&mut self) -> Option<&RowRef>;
3536/// Returns the next [`RowRef`] without advancing the iterator.
37fn peek(&mut self) -> Option<&RowRef>;
3839/// The total number of [`Row`]s this iterator could ever yield.
40 ///
41 /// Note: it _does not_ return the number of rows _remaining_, in otherwords calling `.next()`
42 /// will not change the value returned from this method.
43fn count(&self) -> usize;
4445/// Returns a clone of `self` as a `Box<dyn RowIterator>`.
46fn box_clone(&self) -> Box<dyn RowIterator>;
4748/// Maps the returned [`RowRef`]s from this [`RowIterator`].
49fn map<T, F>(self, f: F) -> MappedRowIterator<Self, F>
50where
51Self: Sized,
52 F: FnMut(&RowRef) -> T,
53 {
54 MappedRowIterator {
55 inner: self,
56 func: f,
57 }
58 }
59}
6061impl<I: RowIterator + ?Sized> RowIterator for Box<I> {
62fn next(&mut self) -> Option<&RowRef> {
63 (**self).next()
64 }
6566fn peek(&mut self) -> Option<&RowRef> {
67 (**self).peek()
68 }
6970fn count(&self) -> usize {
71 (**self).count()
72 }
7374fn box_clone(&self) -> Box<dyn RowIterator> {
75 (**self).box_clone()
76 }
77}
7879impl<I: RowIterator + ?Sized> RowIterator for &mut I {
80fn next(&mut self) -> Option<&RowRef> {
81 (**self).next()
82 }
8384fn peek(&mut self) -> Option<&RowRef> {
85 (**self).peek()
86 }
8788fn count(&self) -> usize {
89 (**self).count()
90 }
9192fn box_clone(&self) -> Box<dyn RowIterator> {
93 (**self).box_clone()
94 }
95}
9697#[derive(Debug)]
98pub struct MappedRowIterator<I: RowIterator, F> {
99 inner: I,
100 func: F,
101}
102103impl<T, F, I: RowIterator> Iterator for MappedRowIterator<I, F>
104where
105F: FnMut(&RowRef) -> T,
106{
107type Item = T;
108109fn next(&mut self) -> Option<Self::Item> {
110let row_ref = self.inner.next()?;
111Some((self.func)(row_ref))
112 }
113}
114115/// Convert a type into a [`RowIterator`].
116pub trait IntoRowIterator {
117type Iter: RowIterator;
118fn into_row_iter(self) -> Self::Iter;
119}
120121impl<T: RowIterator> IntoRowIterator for T {
122type Iter = Self;
123fn into_row_iter(self) -> Self::Iter {
124self
125}
126}
127128/// A [`RowIterator`] for a single [`Row`].
129#[derive(Debug, Clone)]
130pub struct SingleRowIter {
131 row: Arc<Row>,
132 finished: bool,
133}
134135impl RowIterator for SingleRowIter {
136fn next(&mut self) -> Option<&RowRef> {
137if self.finished {
138None
139} else {
140self.finished = true;
141Some(self.row.as_ref())
142 }
143 }
144145fn peek(&mut self) -> Option<&RowRef> {
146if self.finished {
147None
148} else {
149Some(self.row.as_ref())
150 }
151 }
152153fn count(&self) -> usize {
1541
155}
156157fn box_clone(&self) -> Box<dyn RowIterator> {
158 Box::new(self.clone())
159 }
160}
161162impl IntoRowIterator for Row {
163type Iter = SingleRowIter;
164165fn into_row_iter(self) -> Self::Iter {
166 SingleRowIter {
167 row: Arc::new(self),
168 finished: false,
169 }
170 }
171}
172173/// A [`RowIterator`] for a [`Vec`] of [`Row`]s.
174#[derive(Debug, Clone)]
175pub struct VecRowIter {
176 rows: Arc<[Row]>,
177 index: usize,
178}
179180impl RowIterator for VecRowIter {
181fn next(&mut self) -> Option<&RowRef> {
182let row = self.rows.get(self.index).map(|r| r.as_ref())?;
183self.index = self.index.saturating_add(1);
184185Some(row)
186 }
187188fn peek(&mut self) -> Option<&RowRef> {
189self.rows.get(self.index).map(|r| r.as_ref())
190 }
191192fn count(&self) -> usize {
193self.rows.len()
194 }
195196fn box_clone(&self) -> Box<dyn RowIterator> {
197 Box::new(self.clone())
198 }
199}
200201impl IntoRowIterator for Vec<Row> {
202type Iter = VecRowIter;
203204fn into_row_iter(self) -> Self::Iter {
205 VecRowIter {
206 rows: self.into(),
207 index: 0,
208 }
209 }
210}