Skip to content

Commit 04baddb

Browse files
Philippe-Choletjswrenn
authored andcommitted
Make Permutations lazy
To make the `Permutations` adaptor lazy, the operation "prefill the lazy buffer" is now done when handling the initial `Start` state rather than at definition.
1 parent 14d2fa2 commit 04baddb

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

src/permutations.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -49,18 +49,10 @@ where
4949
}
5050

5151
pub fn permutations<I: Iterator>(iter: I, k: usize) -> Permutations<I> {
52-
let mut vals = LazyBuffer::new(iter);
53-
54-
vals.prefill(k);
55-
let enough_vals = vals.len() == k;
56-
57-
let state = if enough_vals {
58-
PermutationState::Start { k }
59-
} else {
60-
PermutationState::End
61-
};
62-
63-
Permutations { vals, state }
52+
Permutations {
53+
vals: LazyBuffer::new(iter),
54+
state: PermutationState::Start { k },
55+
}
6456
}
6557

6658
impl<I> Iterator for Permutations<I>
@@ -78,6 +70,11 @@ where
7870
Some(Vec::new())
7971
}
8072
&mut PermutationState::Start { k } => {
73+
vals.prefill(k);
74+
if vals.len() != k {
75+
*state = PermutationState::End;
76+
return None;
77+
}
8178
*state = PermutationState::Buffered { k, min_n: k };
8279
Some(vals[0..k].to_vec())
8380
}
@@ -166,6 +163,7 @@ impl PermutationState {
166163
(total.unwrap_or(usize::MAX), total)
167164
};
168165
match *self {
166+
Self::Start { k } if n < k => (0, Some(0)),
169167
Self::Start { k } => at_start(n, k),
170168
Self::Buffered { k, min_n } => {
171169
// Same as `Start` minus the previously generated items.

0 commit comments

Comments
 (0)