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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
pub trait ArrayExt<T, const N: usize> {
fn each_ref_ext(&self) -> [&T; N];
fn try_map_ext<F, U, E>(self, f: F) -> Result<[U; N], E>
where
F: FnMut(T) -> Result<U, E>;
}
impl<T> ArrayExt<T, 2> for [T; 2] {
fn each_ref_ext(&self) -> [&T; 2] {
let [a, b] = self;
[a, b]
}
fn try_map_ext<F, U, E>(self, f: F) -> Result<[U; 2], E>
where
F: FnMut(T) -> Result<U, E>,
{
let [a, b] = self.map(f);
Ok([a?, b?])
}
}
impl<T> ArrayExt<T, 4> for [T; 4] {
fn each_ref_ext(&self) -> [&T; 4] {
let [a, b, c, d] = self;
[a, b, c, d]
}
fn try_map_ext<F, U, E>(self, f: F) -> Result<[U; 4], E>
where
F: FnMut(T) -> Result<U, E>,
{
let [a, b, c, d] = self.map(f);
Ok([a?, b?, c?, d?])
}
}
pub trait SliceExt<T> {
fn array_chunks_ext<const N: usize>(&self) -> ArrayChunks<T, N>;
fn array_windows_ext<const N: usize>(&self) -> ArrayWindows<T, N>;
}
impl<T> SliceExt<T> for &[T] {
fn array_chunks_ext<const N: usize>(&self) -> ArrayChunks<T, N> {
ArrayChunks {
slice: self,
index: 0,
}
}
fn array_windows_ext<const N: usize>(&self) -> ArrayWindows<T, N> {
ArrayWindows {
slice: self,
index: 0,
}
}
}
pub struct ArrayChunks<'a, T: 'a, const N: usize> {
slice: &'a [T],
index: usize,
}
impl<'a, T, const N: usize> Iterator for ArrayChunks<'a, T, N> {
type Item = &'a [T; N];
fn next(&mut self) -> Option<Self::Item> {
if self.index + N > self.slice.len() {
return None;
}
let next = &self.slice[self.index..self.index + N];
self.index += N;
let next = next.try_into().unwrap();
Some(next)
}
}
pub struct ArrayWindows<'a, T: 'a, const N: usize> {
slice: &'a [T],
index: usize,
}
impl<'a, T, const N: usize> Iterator for ArrayWindows<'a, T, N> {
type Item = &'a [T; N];
fn next(&mut self) -> Option<Self::Item> {
if self.index + N > self.slice.len() {
return None;
}
let next = &self.slice[self.index..self.index + N];
self.index += 1;
let next = next.try_into().unwrap();
Some(next)
}
}