Need help writing const generic iterator

I want to create an iterator that's similar to windows() but also returns enumerated values. .iter().enumerate().windows(n) wouldn't work since windows works on slices only.

I came up with an ugly function:

/// "lorem" -> [(l, 0)], [(o, 1)], [(r, 2)], [(e, 3)], [(e, 3)], [(m, 4)]
fn enumerated_len2_windows<T: Copy>(arg: &[T], i: &mut usize) -> Option<([(T, usize); 2])> {
    assert!(arg.len() > 1);
    if arg.len() - 1 > *i {
        let result = Some([(arg[*i], *i), (arg[*i + 1], *i + 1)]);
        *i += 2;
        result
    } else if arg.len() - 1 == *i {
        let result = Some([(arg[*i - 1], *i - 1), (arg[*i], *i)]);
        *i += 2;
        result
    } else {
        None
    }
}

Now I want to beautify this code. I think I need to create an iterator that would would also take a (const) generic N argument for windows. I have now idea how to start implementing const generic iterator.

Why not just do this?

.windows(2).enumerate()

The enumerated values must by the indices of the values in the slice itself for my use-case.

Okay, then how about this?

.windows(2).enumerate().map(|(i, win)| [(i, win[0]), (i+1, win[1])])
2 Likes

Thank you this actually works!