Skip to content

Suggestion: map an iterator of indexes to their values in a slice #743

Open
@NightEule5

Description

@NightEule5

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions