I needed a sub-slice around an index: the center, with a given size. While there is a sliding window (iterator) for slices there is no way to get a window around a value.
I wonder if others see value in adding something like this to the slice API. Its not trivial to write yourself as there are some tricky edge cases. I'm not sure if this should live in the std however.
Possible API:
pub fn window(&self, center: usize, window: usize) -> &[T];
Examples:
let slice = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let (center, window_size) = (0, 4);
assert_eq(slice.window(center, window_size), &[0, 1, 2, 3]);
let (center, window_size) = (5, 4);
assert_eq(slice.window(center, window_size), &[4, 5, 6, 7]);
let (center, window_size) = (10, 4);
assert_eq(slice.window(center, window_size), &[7, 8, 9, 10]);
Unresolved questions:
- What should be the name of the method?
- When the window size is even, should there be more elements in front or behind the center? In the examples above I chose more elements after.
- How should the window act around the edges of the slice? Should it:
- keep the window size the same but move the center (like in the example above)
- return a smaller slice.
- What should happen if the slice is smaller then the window?
Main question now:
- Should this live in the stdlib? And if not is there a crate it should live in instead?