array_reshape/lib.rs
1#![no_std]
2#![cfg_attr(feature = "const-trait", feature(const_trait_impl))]
3
4//! Reshaping of arrays, by value, by reference and by mutable reference, all in `const fn`.
5//!
6//! [`<[[T; N]]>::as_flattened()`](slice::as_flattened) and
7//! [`<[T]>::as_chunks()`](slice::as_chunks) in the standard library convert to and from slices,
8//! losing the length in the process. This crate converts between arrays of the same total length
9//! instead, for example `[[T; N]; M]` into `[T; N * M]`:
10//!
11//! ```
12//! use array_reshape::{Flatten, Rechunk, Unflatten};
13//!
14//! let pairs = [[1, 2], [3, 4], [5, 6]];
15//!
16//! let flat: &[u8; 6] = pairs.flatten_ref();
17//! assert_eq!(flat, &[1, 2, 3, 4, 5, 6]);
18//!
19//! let triples = pairs.rechunk_ref::<3, 2>();
20//! assert_eq!(triples, &[[1, 2, 3], [4, 5, 6]]);
21//!
22//! let pairs_again = flat.unflatten::<2, 3>();
23//! assert_eq!(pairs_again, pairs);
24//! ```
25//!
26//! Slices of arrays can be reshaped element by element too:
27//!
28//! ```
29//! use array_reshape::{FlattenEach, UnflattenEach};
30//!
31//! let bytes = [[1, 2, 3, 4], [5, 6, 7, 8]];
32//!
33//! let pairs = bytes.unflatten_each_ref::<2, 2>();
34//! assert_eq!(pairs, &[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]);
35//!
36//! let bytes_again: &[[u8; 4]] = pairs.flatten_each_ref();
37//! assert_eq!(bytes_again, &bytes);
38//! ```
39//!
40//! # `const fn` support
41//!
42//! Trait methods can't be called in `const fn` on stable Rust, which is why every conversion is
43//! also available as a free `const fn` with the same name:
44//!
45//! ```
46//! const FLAT: [u8; 4] = array_reshape::flatten([[1, 2], [3, 4]]);
47//! assert_eq!(FLAT, [1, 2, 3, 4]);
48//! ```
49//!
50//! With the `const-trait` feature, which requires nightly Rust, all traits become `const trait`s,
51//! so their methods can be called in `const fn` directly. Crates calling them in `const fn` need to
52//! enable `const_trait_impl` feature themselves.
53//!
54//! # Output length
55//!
56//! Stable Rust doesn't allow computing array lengths from generic constants yet (which would
57//! require `generic_const_exprs` feature), so the length of the output is a separate generic
58//! parameter, which is usually inferred from the context. The lengths are checked at compile
59//! time, but since the check happens after monomorphization, it is only reported by
60//! `cargo build`, not `cargo check`:
61//!
62//! ```compile_fail
63//! use array_reshape::Flatten;
64//!
65//! let pairs = [[1, 2], [3, 4], [5, 6]];
66//!
67//! let flat: &[u8; 5] = pairs.flatten_ref();
68//! ```
69//!
70//! The check also happens for code that is never executed, but is compiled, like `match` arms
71//! that don't match for a particular set of generic parameters. Convert the input into an array
72//! of a concrete size in such cases first (for example with
73//! [`<[T]>::as_array()`](slice::as_array)).
74
75use core::mem::ManuallyDrop;
76use core::{mem, ptr, slice};
77
78/// Checks at compile time that `inner * outer == len`
79#[inline(always)]
80const fn assert_len<const INNER: usize, const OUTER: usize, const LEN: usize>() {
81 const {
82 assert!(
83 matches!(INNER.checked_mul(OUTER), Some(len) if len == LEN),
84 "Arrays must have the same total number of elements"
85 );
86 }
87}
88
89/// Moves `src` into `Dst` of the same size and layout
90///
91/// # Safety
92/// `Src` and `Dst` must be arrays of the same element type with the same total number of elements.
93#[inline(always)]
94const unsafe fn transmute_array<Src, Dst>(src: Src) -> Dst {
95 let src = ManuallyDrop::new(src);
96 // SAFETY: Guaranteed by function contract, the original value is not dropped
97 unsafe { mem::transmute_copy::<ManuallyDrop<Src>, Dst>(&src) }
98}
99
100/// Flatten `[[T; N]; M]` into `[T; K]`, where `K == N * M`
101#[inline(always)]
102pub const fn flatten<T, const N: usize, const M: usize, const K: usize>(
103 array: [[T; N]; M],
104) -> [T; K] {
105 assert_len::<N, M, K>();
106 // SAFETY: The same element type and the same number of elements, checked above
107 unsafe { transmute_array(array) }
108}
109
110/// Flatten `&[[T; N]; M]` into `&[T; K]`, where `K == N * M`
111#[inline(always)]
112pub const fn flatten_ref<T, const N: usize, const M: usize, const K: usize>(
113 array: &[[T; N]; M],
114) -> &[T; K] {
115 assert_len::<N, M, K>();
116 // SAFETY: The same element type and the same number of elements, checked above
117 unsafe { &*ptr::from_ref(array).cast::<[T; K]>() }
118}
119
120/// Flatten `&mut [[T; N]; M]` into `&mut [T; K]`, where `K == N * M`
121#[inline(always)]
122pub const fn flatten_mut<T, const N: usize, const M: usize, const K: usize>(
123 array: &mut [[T; N]; M],
124) -> &mut [T; K] {
125 assert_len::<N, M, K>();
126 // SAFETY: The same element type and the same number of elements, checked above
127 unsafe { &mut *ptr::from_mut(array).cast::<[T; K]>() }
128}
129
130/// Unflatten `[T; K]` into `[[T; N]; M]`, where `K == N * M`
131#[inline(always)]
132pub const fn unflatten<T, const N: usize, const M: usize, const K: usize>(
133 array: [T; K],
134) -> [[T; N]; M] {
135 assert_len::<N, M, K>();
136 // SAFETY: The same element type and the same number of elements, checked above
137 unsafe { transmute_array(array) }
138}
139
140/// Unflatten `&[T; K]` into `&[[T; N]; M]`, where `K == N * M`
141#[inline(always)]
142pub const fn unflatten_ref<T, const N: usize, const M: usize, const K: usize>(
143 array: &[T; K],
144) -> &[[T; N]; M] {
145 assert_len::<N, M, K>();
146 // SAFETY: The same element type and the same number of elements, checked above
147 unsafe { &*ptr::from_ref(array).cast::<[[T; N]; M]>() }
148}
149
150/// Unflatten `&mut [T; K]` into `&mut [[T; N]; M]`, where `K == N * M`
151#[inline(always)]
152pub const fn unflatten_mut<T, const N: usize, const M: usize, const K: usize>(
153 array: &mut [T; K],
154) -> &mut [[T; N]; M] {
155 assert_len::<N, M, K>();
156 // SAFETY: The same element type and the same number of elements, checked above
157 unsafe { &mut *ptr::from_mut(array).cast::<[[T; N]; M]>() }
158}
159
160/// Change chunk size of `[[T; A]; B]` to get `[[T; C]; D]`, where `A * B == C * D`
161#[inline(always)]
162pub const fn rechunk<T, const A: usize, const B: usize, const C: usize, const D: usize>(
163 array: [[T; A]; B],
164) -> [[T; C]; D] {
165 assert_same_total_len::<A, B, C, D>();
166 // SAFETY: The same element type and the same number of elements, checked above
167 unsafe { transmute_array(array) }
168}
169
170/// Change chunk size of `&[[T; A]; B]` to get `&[[T; C]; D]`, where `A * B == C * D`
171#[inline(always)]
172pub const fn rechunk_ref<T, const A: usize, const B: usize, const C: usize, const D: usize>(
173 array: &[[T; A]; B],
174) -> &[[T; C]; D] {
175 assert_same_total_len::<A, B, C, D>();
176 // SAFETY: The same element type and the same number of elements, checked above
177 unsafe { &*ptr::from_ref(array).cast::<[[T; C]; D]>() }
178}
179
180/// Change chunk size of `&mut [[T; A]; B]` to get `&mut [[T; C]; D]`, where `A * B == C * D`
181#[inline(always)]
182pub const fn rechunk_mut<T, const A: usize, const B: usize, const C: usize, const D: usize>(
183 array: &mut [[T; A]; B],
184) -> &mut [[T; C]; D] {
185 assert_same_total_len::<A, B, C, D>();
186 // SAFETY: The same element type and the same number of elements, checked above
187 unsafe { &mut *ptr::from_mut(array).cast::<[[T; C]; D]>() }
188}
189
190/// Flatten each element of `&[[[T; N]; M]]` to get `&[[T; K]]`, where `K == N * M`
191#[inline(always)]
192pub const fn flatten_each_ref<T, const N: usize, const M: usize, const K: usize>(
193 slice: &[[[T; N]; M]],
194) -> &[[T; K]] {
195 assert_len::<N, M, K>();
196 // SAFETY: The same element type and the same number of elements in each slice element, checked
197 // above
198 unsafe { slice::from_raw_parts(slice.as_ptr().cast::<[T; K]>(), slice.len()) }
199}
200
201/// Flatten each element of `&mut [[[T; N]; M]]` to get `&mut [[T; K]]`, where `K == N * M`
202#[inline(always)]
203pub const fn flatten_each_mut<T, const N: usize, const M: usize, const K: usize>(
204 slice: &mut [[[T; N]; M]],
205) -> &mut [[T; K]] {
206 assert_len::<N, M, K>();
207 // SAFETY: The same element type and the same number of elements in each slice element, checked
208 // above
209 unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr().cast::<[T; K]>(), slice.len()) }
210}
211
212/// Unflatten each element of `&[[T; K]]` to get `&[[[T; N]; M]]`, where `K == N * M`
213#[inline(always)]
214pub const fn unflatten_each_ref<T, const N: usize, const M: usize, const K: usize>(
215 slice: &[[T; K]],
216) -> &[[[T; N]; M]] {
217 assert_len::<N, M, K>();
218 // SAFETY: The same element type and the same number of elements in each slice element, checked
219 // above
220 unsafe { slice::from_raw_parts(slice.as_ptr().cast::<[[T; N]; M]>(), slice.len()) }
221}
222
223/// Unflatten each element of `&mut [[T; K]]` to get `&mut [[[T; N]; M]]`, where `K == N * M`
224#[inline(always)]
225pub const fn unflatten_each_mut<T, const N: usize, const M: usize, const K: usize>(
226 slice: &mut [[T; K]],
227) -> &mut [[[T; N]; M]] {
228 assert_len::<N, M, K>();
229 // SAFETY: The same element type and the same number of elements in each slice element, checked
230 // above
231 unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr().cast::<[[T; N]; M]>(), slice.len()) }
232}
233
234/// Change chunk size of each element of `&[[[T; A]; B]]` to get `&[[[T; C]; D]]`, where
235/// `A * B == C * D`
236#[inline(always)]
237pub const fn rechunk_each_ref<T, const A: usize, const B: usize, const C: usize, const D: usize>(
238 slice: &[[[T; A]; B]],
239) -> &[[[T; C]; D]] {
240 assert_same_total_len::<A, B, C, D>();
241 // SAFETY: The same element type and the same number of elements in each slice element, checked
242 // above
243 unsafe { slice::from_raw_parts(slice.as_ptr().cast::<[[T; C]; D]>(), slice.len()) }
244}
245
246/// Change chunk size of each element of `&mut [[[T; A]; B]]` to get `&mut [[[T; C]; D]]`, where
247/// `A * B == C * D`
248#[inline(always)]
249pub const fn rechunk_each_mut<T, const A: usize, const B: usize, const C: usize, const D: usize>(
250 slice: &mut [[[T; A]; B]],
251) -> &mut [[[T; C]; D]] {
252 assert_same_total_len::<A, B, C, D>();
253 // SAFETY: The same element type and the same number of elements in each slice element, checked
254 // above
255 unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr().cast::<[[T; C]; D]>(), slice.len()) }
256}
257
258/// Checks at compile time that `a * b == c * d`
259#[inline(always)]
260const fn assert_same_total_len<const A: usize, const B: usize, const C: usize, const D: usize>() {
261 const {
262 assert!(
263 matches!(
264 (A.checked_mul(B), C.checked_mul(D)),
265 (Some(input_len), Some(output_len)) if input_len == output_len
266 ),
267 "Arrays must have the same total number of elements"
268 );
269 }
270}
271
272/// Defines reshaping traits, optionally as `const trait`s.
273///
274/// This is a macro because `const trait` syntax is rejected by stable Rust even in code that is
275/// disabled with `#[cfg]`, but not in unexpanded macro invocations.
276macro_rules! define_traits {
277 ($($const:ident)?) => {
278 /// Reshaping of `[[T; N]; M]`, see crate-level documentation for examples.
279 ///
280 /// The same conversions are available as free `const fn`s, see [`flatten()`] and others.
281 pub $($const)? trait Flatten<T, const N: usize, const M: usize>: Sized {
282 /// Flatten into `[T; K]`, where `K == N * M`
283 fn flatten<const K: usize>(self) -> [T; K];
284
285 /// Flatten into `&[T; K]`, where `K == N * M`
286 fn flatten_ref<const K: usize>(&self) -> &[T; K];
287
288 /// Flatten into `&mut [T; K]`, where `K == N * M`
289 fn flatten_mut<const K: usize>(&mut self) -> &mut [T; K];
290 }
291
292 $($const)? impl<T, const N: usize, const M: usize> Flatten<T, N, M> for [[T; N]; M] {
293 #[inline(always)]
294 fn flatten<const K: usize>(self) -> [T; K] {
295 flatten(self)
296 }
297
298 #[inline(always)]
299 fn flatten_ref<const K: usize>(&self) -> &[T; K] {
300 flatten_ref(self)
301 }
302
303 #[inline(always)]
304 fn flatten_mut<const K: usize>(&mut self) -> &mut [T; K] {
305 flatten_mut(self)
306 }
307 }
308
309 /// Changing chunk size of `[[T; N]; M]`, see crate-level documentation for examples.
310 ///
311 /// The same conversions are available as free `const fn`s, see [`rechunk()`] and others.
312 pub $($const)? trait Rechunk<T, const N: usize, const M: usize>: Sized {
313 /// Change chunk size to get `[[T; C]; D]`, where `N * M == C * D`
314 fn rechunk<const C: usize, const D: usize>(self) -> [[T; C]; D];
315
316 /// Change chunk size to get `&[[T; C]; D]`, where `N * M == C * D`
317 fn rechunk_ref<const C: usize, const D: usize>(&self) -> &[[T; C]; D];
318
319 /// Change chunk size to get `&mut [[T; C]; D]`, where `N * M == C * D`
320 fn rechunk_mut<const C: usize, const D: usize>(&mut self) -> &mut [[T; C]; D];
321 }
322
323 $($const)? impl<T, const N: usize, const M: usize> Rechunk<T, N, M> for [[T; N]; M] {
324 #[inline(always)]
325 fn rechunk<const C: usize, const D: usize>(self) -> [[T; C]; D] {
326 rechunk(self)
327 }
328
329 #[inline(always)]
330 fn rechunk_ref<const C: usize, const D: usize>(&self) -> &[[T; C]; D] {
331 rechunk_ref(self)
332 }
333
334 #[inline(always)]
335 fn rechunk_mut<const C: usize, const D: usize>(&mut self) -> &mut [[T; C]; D] {
336 rechunk_mut(self)
337 }
338 }
339
340 /// Reshaping of `[T; K]`, see crate-level documentation for examples.
341 ///
342 /// The same conversions are available as free `const fn`s, see [`unflatten()`] and others.
343 pub $($const)? trait Unflatten<T, const K: usize>: Sized {
344 /// Unflatten into `[[T; N]; M]`, where `K == N * M`
345 fn unflatten<const N: usize, const M: usize>(self) -> [[T; N]; M];
346
347 /// Unflatten into `&[[T; N]; M]`, where `K == N * M`
348 fn unflatten_ref<const N: usize, const M: usize>(&self) -> &[[T; N]; M];
349
350 /// Unflatten into `&mut [[T; N]; M]`, where `K == N * M`
351 fn unflatten_mut<const N: usize, const M: usize>(&mut self) -> &mut [[T; N]; M];
352 }
353
354 $($const)? impl<T, const K: usize> Unflatten<T, K> for [T; K] {
355 #[inline(always)]
356 fn unflatten<const N: usize, const M: usize>(self) -> [[T; N]; M] {
357 unflatten(self)
358 }
359
360 #[inline(always)]
361 fn unflatten_ref<const N: usize, const M: usize>(&self) -> &[[T; N]; M] {
362 unflatten_ref(self)
363 }
364
365 #[inline(always)]
366 fn unflatten_mut<const N: usize, const M: usize>(&mut self) -> &mut [[T; N]; M] {
367 unflatten_mut(self)
368 }
369 }
370 /// Flattening of each element of `[[[T; N]; M]]`, see crate-level documentation for examples.
371 ///
372 /// The same conversions are available as free `const fn`s, see [`flatten_each_ref()`] and
373 /// [`flatten_each_mut()`].
374 pub $($const)? trait FlattenEach<T, const N: usize, const M: usize> {
375 /// Flatten each element to get `&[[T; K]]`, where `K == N * M`
376 fn flatten_each_ref<const K: usize>(&self) -> &[[T; K]];
377
378 /// Flatten each element to get `&mut [[T; K]]`, where `K == N * M`
379 fn flatten_each_mut<const K: usize>(&mut self) -> &mut [[T; K]];
380 }
381
382 $($const)? impl<T, const N: usize, const M: usize> FlattenEach<T, N, M> for [[[T; N]; M]] {
383 #[inline(always)]
384 fn flatten_each_ref<const K: usize>(&self) -> &[[T; K]] {
385 flatten_each_ref(self)
386 }
387
388 #[inline(always)]
389 fn flatten_each_mut<const K: usize>(&mut self) -> &mut [[T; K]] {
390 flatten_each_mut(self)
391 }
392 }
393
394 /// Unflattening of each element of `[[T; K]]`, see crate-level documentation for examples.
395 ///
396 /// The same conversions are available as free `const fn`s, see [`unflatten_each_ref()`]
397 /// and [`unflatten_each_mut()`].
398 pub $($const)? trait UnflattenEach<T, const K: usize> {
399 /// Unflatten each element to get `&[[[T; N]; M]]`, where `K == N * M`
400 fn unflatten_each_ref<const N: usize, const M: usize>(&self) -> &[[[T; N]; M]];
401
402 /// Unflatten each element to get `&mut [[[T; N]; M]]`, where `K == N * M`
403 fn unflatten_each_mut<const N: usize, const M: usize>(&mut self) -> &mut [[[T; N]; M]];
404 }
405
406 $($const)? impl<T, const K: usize> UnflattenEach<T, K> for [[T; K]] {
407 #[inline(always)]
408 fn unflatten_each_ref<const N: usize, const M: usize>(&self) -> &[[[T; N]; M]] {
409 unflatten_each_ref(self)
410 }
411
412 #[inline(always)]
413 fn unflatten_each_mut<const N: usize, const M: usize>(&mut self) -> &mut [[[T; N]; M]] {
414 unflatten_each_mut(self)
415 }
416 }
417
418 /// Changing chunk size of each element of `[[[T; N]; M]]`, see crate-level documentation
419 /// for examples.
420 ///
421 /// The same conversions are available as free `const fn`s, see [`rechunk_each_ref()`] and
422 /// [`rechunk_each_mut()`].
423 pub $($const)? trait RechunkEach<T, const N: usize, const M: usize> {
424 /// Change chunk size of each element to get `&[[[T; C]; D]]`, where `N * M == C * D`
425 fn rechunk_each_ref<const C: usize, const D: usize>(&self) -> &[[[T; C]; D]];
426
427 /// Change chunk size of each element to get `&mut [[[T; C]; D]]`, where
428 /// `N * M == C * D`
429 fn rechunk_each_mut<const C: usize, const D: usize>(&mut self) -> &mut [[[T; C]; D]];
430 }
431
432 $($const)? impl<T, const N: usize, const M: usize> RechunkEach<T, N, M> for [[[T; N]; M]] {
433 #[inline(always)]
434 fn rechunk_each_ref<const C: usize, const D: usize>(&self) -> &[[[T; C]; D]] {
435 rechunk_each_ref(self)
436 }
437
438 #[inline(always)]
439 fn rechunk_each_mut<const C: usize, const D: usize>(&mut self) -> &mut [[[T; C]; D]] {
440 rechunk_each_mut(self)
441 }
442 }
443 };
444}
445
446#[cfg(feature = "const-trait")]
447define_traits!(const);
448#[cfg(not(feature = "const-trait"))]
449define_traits!();