jay_algorithms/
windows.rs1pub trait WindowsExt<T> {
2 type Windows<'a, const N: usize>: Iterator<Item = &'a [T; N]>
3 where
4 Self: 'a,
5 T: 'a;
6
7 fn array_windows_ext<'a, const N: usize>(&'a self) -> Self::Windows<'a, N>;
8}
9
10impl<T> WindowsExt<T> for [T] {
11 type Windows<'a, const N: usize>
12 = WindowsIter<'a, T, N>
13 where
14 T: 'a;
15
16 fn array_windows_ext<'a, const N: usize>(&'a self) -> Self::Windows<'a, N> {
17 WindowsIter { slice: self }
18 }
19}
20
21pub struct WindowsIter<'a, T, const N: usize> {
22 slice: &'a [T],
23}
24
25impl<'a, T, const N: usize> Iterator for WindowsIter<'a, T, N> {
26 type Item = &'a [T; N];
27
28 fn next(&mut self) -> Option<Self::Item> {
29 if self.slice.len() < N {
30 return None;
31 }
32 let res = unsafe { &*self.slice.as_ptr().cast::<[T; N]>() };
33 if N > 0 {
34 self.slice = &self.slice[1..];
35 }
36 Some(res)
37 }
38}