From 04baddb4eb36b1d0bfaa45769902ffd95af94531 Mon Sep 17 00:00:00 2001 From: Philippe-Cholet Date: Fri, 3 Nov 2023 12:44:28 +0100 Subject: [PATCH] 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. --- src/permutations.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/permutations.rs b/src/permutations.rs index 5dd3dbf9a..534ca59c9 100644 --- a/src/permutations.rs +++ b/src/permutations.rs @@ -49,18 +49,10 @@ where } pub fn permutations(iter: I, k: usize) -> Permutations { - let mut vals = LazyBuffer::new(iter); - - vals.prefill(k); - let enough_vals = vals.len() == k; - - let state = if enough_vals { - PermutationState::Start { k } - } else { - PermutationState::End - }; - - Permutations { vals, state } + Permutations { + vals: LazyBuffer::new(iter), + state: PermutationState::Start { k }, + } } impl Iterator for Permutations @@ -78,6 +70,11 @@ where Some(Vec::new()) } &mut PermutationState::Start { k } => { + vals.prefill(k); + if vals.len() != k { + *state = PermutationState::End; + return None; + } *state = PermutationState::Buffered { k, min_n: k }; Some(vals[0..k].to_vec()) } @@ -166,6 +163,7 @@ impl PermutationState { (total.unwrap_or(usize::MAX), total) }; match *self { + Self::Start { k } if n < k => (0, Some(0)), Self::Start { k } => at_start(n, k), Self::Buffered { k, min_n } => { // Same as `Start` minus the previously generated items.