]>
git.proxmox.com Git - rustc.git/blob - vendor/itertools/src/combinations.rs
5 /// An iterator to iterate through all the `n`-length combinations in an iterator.
7 /// See [`.combinations()`](../trait.Itertools.html#method.combinations) for more information.
8 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
9 pub struct Combinations
<I
: Iterator
> {
16 impl<I
> fmt
::Debug
for Combinations
<I
>
17 where I
: Iterator
+ fmt
::Debug
,
20 debug_fmt_fields
!(Combinations
, n
, indices
, pool
, first
);
23 /// Create a new `Combinations` from a clonable iterator.
24 pub fn combinations
<I
>(iter
: I
, n
: usize) -> Combinations
<I
>
27 let mut indices
: Vec
<usize> = Vec
::with_capacity(n
);
31 let mut pool
: LazyBuffer
<I
> = LazyBuffer
::new(iter
);
47 impl<I
> Iterator
for Combinations
<I
>
51 type Item
= Vec
<I
::Item
>;
52 fn next(&mut self) -> Option
<Self::Item
> {
53 let mut pool_len
= self.pool
.len();
54 if self.pool
.is_done() {
55 if pool_len
== 0 || self.n
> pool_len
{
62 } else if self.n
== 0 {
65 // Scan from the end, looking for an index to increment
66 let mut i
: usize = self.n
- 1;
68 // Check if we need to consume more from the iterator
69 if self.indices
[i
] == pool_len
- 1 && !self.pool
.is_done() {
70 if self.pool
.get_next() {
75 while self.indices
[i
] == i
+ pool_len
- self.n
{
79 // Reached the last combination
84 // Increment index, and reset the ones to its right
88 self.indices
[j
] = self.indices
[j
- 1] + 1;
93 // Create result vector based on the indices
94 let mut result
= Vec
::with_capacity(self.n
);
95 for i
in self.indices
.iter() {
96 result
.push(self.pool
[*i
].clone());
103 struct LazyBuffer
<I
: Iterator
> {
106 buffer
: Vec
<I
::Item
>,
109 impl<I
> LazyBuffer
<I
>
112 pub fn new(it
: I
) -> LazyBuffer
<I
> {
114 let mut buffer
= Vec
::new();
116 if let Some(first
) = it
.next() {
129 pub fn len(&self) -> usize {
133 pub fn is_done(&self) -> bool
{
137 pub fn get_next(&mut self) -> bool
{
141 let next_item
= self.it
.next();
155 impl<I
> Index
<usize> for LazyBuffer
<I
>
159 type Output
= I
::Item
;
161 fn index
<'b
>(&'b
self, _index
: usize) -> &'b I
::Item
{
162 self.buffer
.index(_index
)