gat_lending_iterator/adapters/
zip.rs

1use crate::LendingIterator;
2
3/// A lending iterator that iterates two other lending iterators simultaneously.
4///
5/// This `struct` is created by the [`zip`] method on [`LendingIterator`]. See
6/// its documentation for more.
7///
8/// [`LendingIterator`]: crate::LendingIterator
9/// [`zip`]: crate::LendingIterator::zip
10#[derive(Clone, Debug)]
11#[must_use = "iterators are lazy and do nothing unless consumed"]
12pub struct Zip<A, B> {
13    a: A,
14    b: B,
15}
16impl<A, B> Zip<A, B> {
17    pub(crate) fn new(a: A, b: B) -> Zip<A, B> {
18        Zip { a, b }
19    }
20}
21
22impl<A, B> LendingIterator for Zip<A, B>
23where
24    A: LendingIterator,
25    B: LendingIterator,
26{
27    type Item<'a>
28        = (A::Item<'a>, B::Item<'a>)
29    where
30        A: 'a,
31        B: 'a;
32
33    #[inline]
34    fn next(&mut self) -> Option<Self::Item<'_>> {
35        let a = self.a.next()?;
36        let b = self.b.next()?;
37        Some((a, b))
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use crate::{LendingIterator, ToLendingIterator};
44
45    fn make_pair(pair: (i32, i32)) -> (i32, i32) {
46        pair
47    }
48
49    #[test]
50    fn zip_basic() {
51        let result: Vec<_> = (0..3)
52            .into_lending()
53            .zip((10..13).into_lending())
54            .map(make_pair)
55            .into_iter()
56            .collect();
57        assert_eq!(result, vec![(0, 10), (1, 11), (2, 12)]);
58    }
59
60    #[test]
61    fn zip_unequal_lengths() {
62        let result: Vec<_> = (0..5)
63            .into_lending()
64            .zip((10..12).into_lending())
65            .map(make_pair)
66            .into_iter()
67            .collect();
68        assert_eq!(result, vec![(0, 10), (1, 11)]);
69    }
70}