Skip to content

Commit

Permalink
Implement helper on LazyBuffer for getting multiple elements by index
Browse files Browse the repository at this point in the history
  • Loading branch information
kinto-b authored and Philippe-Cholet committed Apr 18, 2024
1 parent ed695af commit f7d557d
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 21 deletions.
8 changes: 2 additions & 6 deletions src/combinations.rs
Expand Up @@ -162,14 +162,10 @@ where
return None;
}

Some(self.indices.iter().map(|i| self.pool[*i].clone()).collect())
Some(self.pool.get_at(&self.indices))
}

fn nth(&mut self, n: usize) -> Option<Self::Item> {
if n == 0 {
return self.next();
}

let done = if self.first {
self.init()
} else {
Expand All @@ -186,7 +182,7 @@ where
}
}

Some(self.indices.iter().map(|i| self.pool[*i].clone()).collect())
Some(self.pool.get_at(&self.indices))
}

fn size_hint(&self) -> (usize, Option<usize>) {
Expand Down
15 changes: 2 additions & 13 deletions src/combinations_with_replacement.rs
Expand Up @@ -30,17 +30,6 @@ where
debug_fmt_fields!(CombinationsWithReplacement, indices, pool, first);
}

impl<I> CombinationsWithReplacement<I>
where
I: Iterator,
I::Item: Clone,
{
/// Map the current mask over the pool to get an output combination
fn current(&self) -> Vec<I::Item> {
self.indices.iter().map(|i| self.pool[*i].clone()).collect()
}
}

/// Create a new `CombinationsWithReplacement` from a clonable iterator.
pub fn combinations_with_replacement<I>(iter: I, k: usize) -> CombinationsWithReplacement<I>
where
Expand Down Expand Up @@ -72,7 +61,7 @@ where
// Otherwise, yield the initial state
} else {
self.first = false;
Some(self.current())
Some(self.pool.get_at(&self.indices))
};
}

Expand All @@ -97,7 +86,7 @@ where
for indices_index in increment_from..self.indices.len() {
self.indices[indices_index] = increment_value;
}
Some(self.current())
Some(self.pool.get_at(&self.indices))
}
// Otherwise, we're done
None => None,
Expand Down
10 changes: 10 additions & 0 deletions src/lazy_buffer.rs
Expand Up @@ -51,6 +51,16 @@ where
}
}

impl<I> LazyBuffer<I>
where
I: Iterator,
I::Item: Clone,
{
pub fn get_at(&self, indices: &[usize]) -> Vec<I::Item> {
indices.iter().map(|i| self.buffer[*i].clone()).collect()
}
}

impl<I, J> Index<J> for LazyBuffer<I>
where
I: Iterator,
Expand Down
4 changes: 2 additions & 2 deletions src/permutations.rs
Expand Up @@ -99,7 +99,7 @@ where
return None;
}
}
let item = indices[0..*k].iter().map(|&i| vals[i].clone()).collect();
let item = vals.get_at(&indices[0..*k]);
*state = PermutationState::Loaded { indices, cycles };
Some(item)
}
Expand All @@ -110,7 +110,7 @@ where
return None;
}
let k = cycles.len();
Some(indices[0..k].iter().map(|&i| vals[i].clone()).collect())
Some(vals.get_at(&indices[0..k]))
}
PermutationState::End => None,
}
Expand Down

0 comments on commit f7d557d

Please sign in to comment.