Skip to content

Commit

Permalink
MultiProduct::size_hint
Browse files Browse the repository at this point in the history
Similar to `count` but with "size hint" operations.
  • Loading branch information
Philippe-Cholet committed Jan 3, 2024
1 parent ab2d72a commit 1546dcb
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/adaptors/multi_product.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

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`.
Expand Down Expand Up @@ -152,6 +154,27 @@ where
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
match &self.0 {
None => (0, Some(0)),
Some(MultiProductInner { iters, cur }) => {
if cur.is_none() {
iters
.iter()
.map(|iter| iter.iter_orig.size_hint())
.fold((1, Some(1)), size_hint::mul)
} else 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 {
(0, Some(0))
}
}
}
}

fn last(self) -> Option<Self::Item> {
let MultiProductInner { iters, cur } = self.0?;
if let Some(values) = cur {
Expand Down

0 comments on commit 1546dcb

Please sign in to comment.