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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#![cfg(feature = "use_alloc")]
use Option::{self as State, None as ProductEnded, Some as ProductInProgress};
use Option::{self as CurrentItems, None as NotYetPopulated, Some as Populated};

use alloc::vec::Vec;

use crate::size_hint;

#[derive(Clone)]
/// An iterator adaptor that iterates over the cartesian product of
/// multiple iterators of type `I`.
///
/// An iterator element type is `Vec<I::Item>`.
///
/// See [`.multi_cartesian_product()`](crate::Itertools::multi_cartesian_product)
/// for more information.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct MultiProduct<I>(State<MultiProductInner<I>>)
where
    I: Iterator + Clone,
    I::Item: Clone;

#[derive(Clone)]
/// Internals for `MultiProduct`.
struct MultiProductInner<I>
where
    I: Iterator + Clone,
    I::Item: Clone,
{
    /// Holds the iterators.
    iters: Vec<MultiProductIter<I>>,
    /// Not populated at the beginning then it holds the current item of each iterator.
    cur: CurrentItems<Vec<I::Item>>,
}

impl<I> std::fmt::Debug for MultiProduct<I>
where
    I: Iterator + Clone + std::fmt::Debug,
    I::Item: Clone + std::fmt::Debug,
{
    debug_fmt_fields!(MultiProduct, 0);
}

impl<I> std::fmt::Debug for MultiProductInner<I>
where
    I: Iterator + Clone + std::fmt::Debug,
    I::Item: Clone + std::fmt::Debug,
{
    debug_fmt_fields!(MultiProductInner, iters, cur);
}

/// Create a new cartesian product iterator over an arbitrary number
/// of iterators of the same type.
///
/// Iterator element is of type `Vec<H::Item::Item>`.
pub fn multi_cartesian_product<H>(iters: H) -> MultiProduct<<H::Item as IntoIterator>::IntoIter>
where
    H: Iterator,
    H::Item: IntoIterator,
    <H::Item as IntoIterator>::IntoIter: Clone,
    <H::Item as IntoIterator>::Item: Clone,
{
    let inner = MultiProductInner {
        iters: iters
            .map(|i| MultiProductIter::new(i.into_iter()))
            .collect(),
        cur: NotYetPopulated,
    };
    MultiProduct(ProductInProgress(inner))
}

#[derive(Clone, Debug)]
/// Holds the state of a single iterator within a `MultiProduct`.
struct MultiProductIter<I>
where
    I: Iterator + Clone,
    I::Item: Clone,
{
    iter: I,
    iter_orig: I,
}

impl<I> MultiProductIter<I>
where
    I: Iterator + Clone,
    I::Item: Clone,
{
    fn new(iter: I) -> Self {
        Self {
            iter: iter.clone(),
            iter_orig: iter,
        }
    }
}

impl<I> Iterator for MultiProduct<I>
where
    I: Iterator + Clone,
    I::Item: Clone,
{
    type Item = Vec<I::Item>;

    fn next(&mut self) -> Option<Self::Item> {
        // This fuses the iterator.
        let inner = self.0.as_mut()?;
        match &mut inner.cur {
            Populated(values) => {
                debug_assert!(!inner.iters.is_empty());
                // Find (from the right) a non-finished iterator and
                // reset the finished ones encountered.
                for (iter, item) in inner.iters.iter_mut().zip(values.iter_mut()).rev() {
                    if let Some(new) = iter.iter.next() {
                        *item = new;
                        return Some(values.clone());
                    } else {
                        iter.iter = iter.iter_orig.clone();
                        // `cur` is populated so the untouched `iter_orig` can not be empty.
                        *item = iter.iter.next().unwrap();
                    }
                }
                self.0 = ProductEnded;
                None
            }
            // Only the first time.
            NotYetPopulated => {
                let next: Option<Vec<_>> = inner.iters.iter_mut().map(|i| i.iter.next()).collect();
                if next.is_none() || inner.iters.is_empty() {
                    // This cartesian product had at most one item to generate and now ends.
                    self.0 = ProductEnded;
                } else {
                    inner.cur.clone_from(&next);
                }
                next
            }
        }
    }

    fn count(self) -> usize {
        match self.0 {
            ProductEnded => 0,
            // The iterator is fresh so the count is the product of the length of each iterator:
            // - If one of them is empty, stop counting.
            // - Less `count()` calls than the general case.
            ProductInProgress(MultiProductInner {
                iters,
                cur: NotYetPopulated,
            }) => iters
                .into_iter()
                .map(|iter| iter.iter_orig.count())
                .try_fold(1, |product, count| {
                    if count == 0 {
                        None
                    } else {
                        Some(product * count)
                    }
                })
                .unwrap_or_default(),
            // The general case.
            ProductInProgress(MultiProductInner {
                iters,
                cur: Populated(_),
            }) => iters.into_iter().fold(0, |mut acc, iter| {
                if acc != 0 {
                    acc *= iter.iter_orig.count();
                }
                acc + iter.iter.count()
            }),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.0 {
            ProductEnded => (0, Some(0)),
            ProductInProgress(MultiProductInner {
                iters,
                cur: NotYetPopulated,
            }) => iters
                .iter()
                .map(|iter| iter.iter_orig.size_hint())
                .fold((1, Some(1)), size_hint::mul),
            ProductInProgress(MultiProductInner {
                iters,
                cur: Populated(_),
            }) => {
                if let [first, tail @ ..] = &iters[..] {
                    tail.iter().fold(first.iter.size_hint(), |mut sh, iter| {
                        sh = size_hint::mul(sh, iter.iter_orig.size_hint());
                        size_hint::add(sh, iter.iter.size_hint())
                    })
                } else {
                    // Since it is populated, this cartesian product has started so `iters` is not empty.
                    unreachable!()
                }
            }
        }
    }

    fn last(self) -> Option<Self::Item> {
        let MultiProductInner { iters, cur } = self.0?;
        // Collect the last item of each iterator of the product.
        if let Populated(values) = cur {
            let mut count = iters.len();
            let last = iters
                .into_iter()
                .zip(values)
                .map(|(i, value)| {
                    i.iter.last().unwrap_or_else(|| {
                        // The iterator is empty, use its current `value`.
                        count -= 1;
                        value
                    })
                })
                .collect();
            if count == 0 {
                // `values` was the last item.
                None
            } else {
                Some(last)
            }
        } else {
            iters.into_iter().map(|i| i.iter.last()).collect()
        }
    }
}

impl<I> std::iter::FusedIterator for MultiProduct<I>
where
    I: Iterator + Clone,
    I::Item: Clone,
{
}