Slice index ranges


#1

[This is a tiny proposal for the std library. I am not sure how much commonly useful it is, if it’s against the idea of using ranges instead of indexing into slices, if it’s not too much small for inclusion, etc.]

Sometimes I have to loop on the range of indexes of a slice or I need such interval of indexes in a iterators chains. So I think it’s handy to have something similar to HashMap::keys() for slices and arrays too:

use std::ops::Range;

trait IndexRange {
    fn range(&self) -> Range<usize>;
}

impl<T> IndexRange for Vec<T> {
    #[inline]
    fn range(&self) -> Range<usize> {
        (0 .. self.len())
    }
}

impl<'a, T> IndexRange for &'a [T] {
    #[inline]
    fn range(&self) -> Range<usize> {
        (0 .. self.len())
    }
}

macro_rules! index_range_impls {
    ($($N:expr)+) => {
        $(
            impl<'a, T> IndexRange for &'a [T; $N] {
                #[inline]
                fn range(&self) -> Range<usize> {
                    (0 .. self.len())
                }
            }
        )+
    }
}

index_range_impls!{
     0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
     18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
}

This idea is also similar to the 'Range attribute in Ada language:
https://en.wikibooks.org/wiki/Ada_Programming/Attributes/'Range


#2

Why not just use enumerate on the iterator? I also feel like adding a whole other trait just to avoid 0..slice.len() doesn’t really carry its weight.