Skip to content

Commit 05c2edf

Browse files
MultiProduct: add comments
1 parent 0c23808 commit 05c2edf

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/adaptors/multi_product.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,13 @@ where
102102
type Item = Vec<I::Item>;
103103

104104
fn next(&mut self) -> Option<Self::Item> {
105+
// This fuses the iterator.
105106
let inner = self.0.as_mut()?;
106107
match &mut inner.cur {
107108
Some(values) => {
108109
debug_assert!(!inner.iters.is_empty());
110+
// Find (from the right) a non-finished iterator and
111+
// reset the finished ones encountered.
109112
for (iter, item) in inner.iters.iter_mut().zip(values.iter_mut()).rev() {
110113
if let Some(new) = iter.iter.next() {
111114
*item = new;
@@ -136,9 +139,12 @@ where
136139

137140
fn count(self) -> usize {
138141
match self.0 {
139-
None => 0,
142+
None => 0, // The cartesian product has ended.
140143
Some(MultiProductInner { iters, cur }) => {
141144
if cur.is_none() {
145+
// The iterator is fresh so the count is the product of the length of each iterator:
146+
// - If one of them is empty, stop counting.
147+
// - Less `count()` calls than the general case.
142148
iters
143149
.into_iter()
144150
.map(|iter| iter.iter_orig.count())
@@ -151,6 +157,7 @@ where
151157
})
152158
.unwrap_or_default()
153159
} else {
160+
// The general case.
154161
iters.into_iter().fold(0, |mut acc, iter| {
155162
if acc != 0 {
156163
acc *= iter.iter_orig.count();
@@ -164,7 +171,7 @@ where
164171

165172
fn size_hint(&self) -> (usize, Option<usize>) {
166173
match &self.0 {
167-
None => (0, Some(0)),
174+
None => (0, Some(0)), // The cartesian product has ended.
168175
Some(MultiProductInner { iters, cur }) => {
169176
if cur.is_none() {
170177
iters
@@ -186,13 +193,15 @@ where
186193

187194
fn last(self) -> Option<Self::Item> {
188195
let MultiProductInner { iters, cur } = self.0?;
196+
// Collect the last item of each iterator of the product.
189197
if let Some(values) = cur {
190198
let mut count = iters.len();
191199
let last = iters
192200
.into_iter()
193201
.zip(values)
194202
.map(|(i, value)| {
195203
i.iter.last().unwrap_or_else(|| {
204+
// The iterator is empty, use its current `value`.
196205
count -= 1;
197206
value
198207
})

0 commit comments

Comments
 (0)