Open
Description
I've run into a pattern that I'm surprised isn't an iterator method or extension already (or if it is, I haven't found it):
let slice = b"Hello world!";
let range = 2..9;
for byte in range.map(|i| &slice[i]) {
// ...
}
An map_index
extension could be added for this, like:
struct MapIndex<'a, I, T> {
iter: I,
source: &'a T
}
impl<'a, I: Iterator, T: Index<I::Item>> Iterator for MapIndex<'a, I, T>
where T::Output: Sized + 'a {
type Item = &'a T::Output;
fn next(&mut self) -> Option<&'a T::Output> {
self.iter.next().map(|index|
&self.source[index]
)
}
}
trait Itertools: Iterator {
fn map_index<T: Index<Self::Item>>(self, source: &T) -> MapIndex<Self, T>
where T::Output: Sized,
Self: Sized {
MapIndex { iter: self, source }
}
}
Metadata
Metadata
Assignees
Labels
No labels