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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use core::{
borrow::{Borrow, BorrowMut},
ops::{Deref, DerefMut},
slice::{Iter, IterMut},
};
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct ArrayWrapper<T, const N: usize>(
pub [T; N],
);
impl<T, const N: usize> ArrayWrapper<T, N> {
#[inline]
pub fn from_fn(mut cb: impl FnMut(usize) -> T) -> Self {
let mut idx = 0;
Self([(); N].map(|_| {
let res = cb(idx);
idx = idx.wrapping_add(1);
res
}))
}
#[inline]
pub fn try_from_fn<E>(cb: impl FnMut(usize) -> Result<T, E>) -> Result<Self, E> {
Ok(Self(here_be_dragons::try_from_fn(cb)?))
}
}
impl<T, const N: usize> AsRef<[T; N]> for ArrayWrapper<T, N> {
#[inline]
fn as_ref(&self) -> &[T; N] {
self
}
}
impl<T, const N: usize> AsMut<[T; N]> for ArrayWrapper<T, N> {
#[inline]
fn as_mut(&mut self) -> &mut [T; N] {
self
}
}
impl<T, const N: usize> Borrow<[T; N]> for ArrayWrapper<T, N> {
#[inline]
fn borrow(&self) -> &[T; N] {
self
}
}
impl<T, const N: usize> BorrowMut<[T; N]> for ArrayWrapper<T, N> {
#[inline]
fn borrow_mut(&mut self) -> &mut [T; N] {
self
}
}
impl<T, const N: usize> Default for ArrayWrapper<T, N>
where
T: Default,
{
#[inline]
fn default() -> Self {
Self::from_fn(|_| T::default())
}
}
impl<T, const N: usize> Deref for ArrayWrapper<T, N> {
type Target = [T; N];
#[inline]
fn deref(&self) -> &[T; N] {
&self.0
}
}
impl<T, const N: usize> DerefMut for ArrayWrapper<T, N> {
#[inline]
fn deref_mut(&mut self) -> &mut [T; N] {
&mut self.0
}
}
impl<T, const N: usize> From<[T; N]> for ArrayWrapper<T, N> {
#[inline]
fn from(from: [T; N]) -> Self {
Self(from)
}
}
impl<'array, T, const N: usize> IntoIterator for &'array ArrayWrapper<T, N> {
type IntoIter = Iter<'array, T>;
type Item = &'array T;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<'array, T, const N: usize> IntoIterator for &'array mut ArrayWrapper<T, N> {
type IntoIter = IterMut<'array, T>;
type Item = &'array mut T;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.0.iter_mut()
}
}
mod here_be_dragons {
#![allow(clippy::as_conversions, clippy::mem_forget, trivial_casts, unsafe_code)]
use core::{
mem::{self, MaybeUninit},
ptr,
};
#[inline]
pub(super) fn try_from_fn<E, T, const N: usize>(
cb: impl FnMut(usize) -> Result<T, E>,
) -> Result<[T; N], E> {
let mut iter = (0..N).map(cb);
debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
debug_assert!(N <= iter.size_hint().0);
unsafe { try_collect_into_array(&mut iter).unwrap_unchecked() }
}
unsafe fn array_assume_init<T, const N: usize>(array: [MaybeUninit<T>; N]) -> [T; N] {
(&array as *const _ as *const [T; N]).read()
}
fn try_collect_into_array<E, T, const N: usize>(
iter: &mut impl Iterator<Item = Result<T, E>>,
) -> Option<Result<[T; N], E>> {
if N == 0 {
return unsafe { Some(mem::zeroed()) };
}
struct Guard<'array, T, const N: usize> {
array_mut: &'array mut [MaybeUninit<T>; N],
initialized: usize,
}
impl<T, const N: usize> Drop for Guard<'_, T, N> {
fn drop(&mut self) {
debug_assert!(self.initialized <= N);
unsafe {
ptr::drop_in_place(slice_assume_init_mut(
self.array_mut.get_unchecked_mut(..self.initialized),
));
}
}
}
let mut array = uninit_array::<T, N>();
let mut guard = Guard { array_mut: &mut array, initialized: 0 };
for item_rslt in iter {
let item = match item_rslt {
Err(err) => {
return Some(Err(err));
}
Ok(elem) => elem,
};
unsafe {
let _ = guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
}
guard.initialized = guard.initialized.wrapping_add(1);
if guard.initialized == N {
mem::forget(guard);
let out = unsafe { array_assume_init(array) };
return Some(Ok(out));
}
}
None
}
unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] {
&mut *(slice as *mut [MaybeUninit<T>] as *mut [T])
}
const fn uninit_array<T, const LEN: usize>() -> [MaybeUninit<T>; LEN] {
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() }
}
}
#[cfg(feature = "serde")]
mod serde {
use crate::{ArrayWrapper, ArrayWrapperRef};
use core::{fmt::Formatter, marker::PhantomData};
use serde::{
de::{self, SeqAccess, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
impl<'de, T, const N: usize> Deserialize<'de> for ArrayWrapper<T, N>
where
T: Deserialize<'de>,
{
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ArrayVisitor<T, const N: usize>(PhantomData<T>);
impl<'de, T, const N: usize> Visitor<'de> for ArrayVisitor<T, N>
where
T: Deserialize<'de>,
{
type Value = ArrayWrapper<T, N>;
#[inline]
fn expecting(&self, formatter: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
formatter.write_fmt(format_args!("an array with {} elements", N))
}
#[inline]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
ArrayWrapper::try_from_fn(|_| {
seq.next_element::<T>()?.ok_or_else(|| {
de::Error::invalid_length(N, &"Array need more data to be constructed")
})
})
}
}
deserializer.deserialize_tuple(N, ArrayVisitor::<T, N>(PhantomData))
}
}
impl<T, const N: usize> Serialize for ArrayWrapper<T, N>
where
T: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
ArrayWrapperRef::from(&self.0).serialize(serializer)
}
}
}