Skip to content

Commit

Permalink
Make Permutations lazy
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Philippe-Cholet authored and jswrenn committed Nov 3, 2023
1 parent 14d2fa2 commit 04baddb
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/permutations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,10 @@ where
}

pub fn permutations<I: Iterator>(iter: I, k: usize) -> Permutations<I> {
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<I> Iterator for Permutations<I>
Expand All @@ -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())
}
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit 04baddb

Please sign in to comment.