Skip to main content

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//! # `const fn` support
27//!
28//! Trait methods can't be called in `const fn` on stable Rust, which is why every conversion is
29//! also available as a free `const fn` with the same name:
30//!
31//! ```
32//! const FLAT: [u8; 4] = array_reshape::flatten([[1, 2], [3, 4]]);
33//! assert_eq!(FLAT, [1, 2, 3, 4]);
34//! ```
35//!
36//! With the `const-trait` feature, which requires nightly Rust, [`Flatten`], [`Rechunk`] and
37//! [`Unflatten`] become `const trait`s, so their methods can be called in `const fn` directly.
38//! Crates calling them in `const fn` need to enable `const_trait_impl` feature themselves.
39//!
40//! # Output length
41//!
42//! Stable Rust doesn't allow computing array lengths from generic constants yet (which would
43//! require `generic_const_exprs` feature), so the length of the output is a separate generic
44//! parameter, which is usually inferred from the context. The lengths are checked at compile
45//! time, but since the check happens after monomorphization, it is only reported by
46//! `cargo build`, not `cargo check`:
47//!
48//! ```compile_fail
49//! use array_reshape::Flatten;
50//!
51//! let pairs = [[1, 2], [3, 4], [5, 6]];
52//!
53//! let flat: &[u8; 5] = pairs.flatten_ref();
54//! ```
55//!
56//! The check also happens for code that is never executed, but is compiled, like `match` arms
57//! that don't match for a particular set of generic parameters. Convert the input into an array
58//! of a concrete size in such cases first (for example with
59//! [`<[T]>::as_array()`](slice::as_array)).
60
61use core::mem::ManuallyDrop;
62use core::{mem, ptr};
63
64/// Checks at compile time that `inner * outer == len`
65#[inline(always)]
66const fn assert_len<const INNER: usize, const OUTER: usize, const LEN: usize>() {
67    const {
68        assert!(
69            matches!(INNER.checked_mul(OUTER), Some(len) if len == LEN),
70            "Arrays must have the same total number of elements"
71        );
72    }
73}
74
75/// Moves `src` into `Dst` of the same size and layout
76///
77/// # Safety
78/// `Src` and `Dst` must be arrays of the same element type with the same total number of elements.
79#[inline(always)]
80const unsafe fn transmute_array<Src, Dst>(src: Src) -> Dst {
81    let src = ManuallyDrop::new(src);
82    // SAFETY: Guaranteed by function contract, the original value is not dropped
83    unsafe { mem::transmute_copy::<ManuallyDrop<Src>, Dst>(&src) }
84}
85
86/// Flatten `[[T; N]; M]` into `[T; K]`, where `K == N * M`
87#[inline(always)]
88pub const fn flatten<T, const N: usize, const M: usize, const K: usize>(
89    array: [[T; N]; M],
90) -> [T; K] {
91    assert_len::<N, M, K>();
92    // SAFETY: The same element type and the same number of elements, checked above
93    unsafe { transmute_array(array) }
94}
95
96/// Flatten `&[[T; N]; M]` into `&[T; K]`, where `K == N * M`
97#[inline(always)]
98pub const fn flatten_ref<T, const N: usize, const M: usize, const K: usize>(
99    array: &[[T; N]; M],
100) -> &[T; K] {
101    assert_len::<N, M, K>();
102    // SAFETY: The same element type and the same number of elements, checked above
103    unsafe { &*ptr::from_ref(array).cast::<[T; K]>() }
104}
105
106/// Flatten `&mut [[T; N]; M]` into `&mut [T; K]`, where `K == N * M`
107#[inline(always)]
108pub const fn flatten_mut<T, const N: usize, const M: usize, const K: usize>(
109    array: &mut [[T; N]; M],
110) -> &mut [T; K] {
111    assert_len::<N, M, K>();
112    // SAFETY: The same element type and the same number of elements, checked above
113    unsafe { &mut *ptr::from_mut(array).cast::<[T; K]>() }
114}
115
116/// Unflatten `[T; K]` into `[[T; N]; M]`, where `K == N * M`
117#[inline(always)]
118pub const fn unflatten<T, const N: usize, const M: usize, const K: usize>(
119    array: [T; K],
120) -> [[T; N]; M] {
121    assert_len::<N, M, K>();
122    // SAFETY: The same element type and the same number of elements, checked above
123    unsafe { transmute_array(array) }
124}
125
126/// Unflatten `&[T; K]` into `&[[T; N]; M]`, where `K == N * M`
127#[inline(always)]
128pub const fn unflatten_ref<T, const N: usize, const M: usize, const K: usize>(
129    array: &[T; K],
130) -> &[[T; N]; M] {
131    assert_len::<N, M, K>();
132    // SAFETY: The same element type and the same number of elements, checked above
133    unsafe { &*ptr::from_ref(array).cast::<[[T; N]; M]>() }
134}
135
136/// Unflatten `&mut [T; K]` into `&mut [[T; N]; M]`, where `K == N * M`
137#[inline(always)]
138pub const fn unflatten_mut<T, const N: usize, const M: usize, const K: usize>(
139    array: &mut [T; K],
140) -> &mut [[T; N]; M] {
141    assert_len::<N, M, K>();
142    // SAFETY: The same element type and the same number of elements, checked above
143    unsafe { &mut *ptr::from_mut(array).cast::<[[T; N]; M]>() }
144}
145
146/// Change chunk size of `[[T; A]; B]` to get `[[T; C]; D]`, where `A * B == C * D`
147#[inline(always)]
148pub const fn rechunk<T, const A: usize, const B: usize, const C: usize, const D: usize>(
149    array: [[T; A]; B],
150) -> [[T; C]; D] {
151    assert_same_total_len::<A, B, C, D>();
152    // SAFETY: The same element type and the same number of elements, checked above
153    unsafe { transmute_array(array) }
154}
155
156/// Change chunk size of `&[[T; A]; B]` to get `&[[T; C]; D]`, where `A * B == C * D`
157#[inline(always)]
158pub const fn rechunk_ref<T, const A: usize, const B: usize, const C: usize, const D: usize>(
159    array: &[[T; A]; B],
160) -> &[[T; C]; D] {
161    assert_same_total_len::<A, B, C, D>();
162    // SAFETY: The same element type and the same number of elements, checked above
163    unsafe { &*ptr::from_ref(array).cast::<[[T; C]; D]>() }
164}
165
166/// Change chunk size of `&mut [[T; A]; B]` to get `&mut [[T; C]; D]`, where `A * B == C * D`
167#[inline(always)]
168pub const fn rechunk_mut<T, const A: usize, const B: usize, const C: usize, const D: usize>(
169    array: &mut [[T; A]; B],
170) -> &mut [[T; C]; D] {
171    assert_same_total_len::<A, B, C, D>();
172    // SAFETY: The same element type and the same number of elements, checked above
173    unsafe { &mut *ptr::from_mut(array).cast::<[[T; C]; D]>() }
174}
175
176/// Checks at compile time that `a * b == c * d`
177#[inline(always)]
178const fn assert_same_total_len<const A: usize, const B: usize, const C: usize, const D: usize>() {
179    const {
180        assert!(
181            matches!(
182                (A.checked_mul(B), C.checked_mul(D)),
183                (Some(input_len), Some(output_len)) if input_len == output_len
184            ),
185            "Arrays must have the same total number of elements"
186        );
187    }
188}
189
190/// Defines [`Flatten`], [`Rechunk`] and [`Unflatten`], optionally as `const trait`s.
191///
192/// This is a macro because `const trait` syntax is rejected by stable Rust even in code that is
193/// disabled with `#[cfg]`, but not in unexpanded macro invocations.
194macro_rules! define_traits {
195    ($($const:ident)?) => {
196        /// Reshaping of `[[T; N]; M]`, see crate-level documentation for examples.
197        ///
198        /// The same conversions are available as free `const fn`s, see [`flatten()`] and others.
199        pub $($const)? trait Flatten<T, const N: usize, const M: usize>: Sized {
200            /// Flatten into `[T; K]`, where `K == N * M`
201            fn flatten<const K: usize>(self) -> [T; K];
202
203            /// Flatten into `&[T; K]`, where `K == N * M`
204            fn flatten_ref<const K: usize>(&self) -> &[T; K];
205
206            /// Flatten into `&mut [T; K]`, where `K == N * M`
207            fn flatten_mut<const K: usize>(&mut self) -> &mut [T; K];
208        }
209
210        $($const)? impl<T, const N: usize, const M: usize> Flatten<T, N, M> for [[T; N]; M] {
211            #[inline(always)]
212            fn flatten<const K: usize>(self) -> [T; K] {
213                flatten(self)
214            }
215
216            #[inline(always)]
217            fn flatten_ref<const K: usize>(&self) -> &[T; K] {
218                flatten_ref(self)
219            }
220
221            #[inline(always)]
222            fn flatten_mut<const K: usize>(&mut self) -> &mut [T; K] {
223                flatten_mut(self)
224            }
225        }
226
227        /// Changing chunk size of `[[T; N]; M]`, see crate-level documentation for examples.
228        ///
229        /// The same conversions are available as free `const fn`s, see [`rechunk()`] and others.
230        pub $($const)? trait Rechunk<T, const N: usize, const M: usize>: Sized {
231            /// Change chunk size to get `[[T; C]; D]`, where `N * M == C * D`
232            fn rechunk<const C: usize, const D: usize>(self) -> [[T; C]; D];
233
234            /// Change chunk size to get `&[[T; C]; D]`, where `N * M == C * D`
235            fn rechunk_ref<const C: usize, const D: usize>(&self) -> &[[T; C]; D];
236
237            /// Change chunk size to get `&mut [[T; C]; D]`, where `N * M == C * D`
238            fn rechunk_mut<const C: usize, const D: usize>(&mut self) -> &mut [[T; C]; D];
239        }
240
241        $($const)? impl<T, const N: usize, const M: usize> Rechunk<T, N, M> for [[T; N]; M] {
242            #[inline(always)]
243            fn rechunk<const C: usize, const D: usize>(self) -> [[T; C]; D] {
244                rechunk(self)
245            }
246
247            #[inline(always)]
248            fn rechunk_ref<const C: usize, const D: usize>(&self) -> &[[T; C]; D] {
249                rechunk_ref(self)
250            }
251
252            #[inline(always)]
253            fn rechunk_mut<const C: usize, const D: usize>(&mut self) -> &mut [[T; C]; D] {
254                rechunk_mut(self)
255            }
256        }
257
258        /// Reshaping of `[T; K]`, see crate-level documentation for examples.
259        ///
260        /// The same conversions are available as free `const fn`s, see [`unflatten()`] and others.
261        pub $($const)? trait Unflatten<T, const K: usize>: Sized {
262            /// Unflatten into `[[T; N]; M]`, where `K == N * M`
263            fn unflatten<const N: usize, const M: usize>(self) -> [[T; N]; M];
264
265            /// Unflatten into `&[[T; N]; M]`, where `K == N * M`
266            fn unflatten_ref<const N: usize, const M: usize>(&self) -> &[[T; N]; M];
267
268            /// Unflatten into `&mut [[T; N]; M]`, where `K == N * M`
269            fn unflatten_mut<const N: usize, const M: usize>(&mut self) -> &mut [[T; N]; M];
270        }
271
272        $($const)? impl<T, const K: usize> Unflatten<T, K> for [T; K] {
273            #[inline(always)]
274            fn unflatten<const N: usize, const M: usize>(self) -> [[T; N]; M] {
275                unflatten(self)
276            }
277
278            #[inline(always)]
279            fn unflatten_ref<const N: usize, const M: usize>(&self) -> &[[T; N]; M] {
280                unflatten_ref(self)
281            }
282
283            #[inline(always)]
284            fn unflatten_mut<const N: usize, const M: usize>(&mut self) -> &mut [[T; N]; M] {
285                unflatten_mut(self)
286            }
287        }
288    };
289}
290
291#[cfg(feature = "const-trait")]
292define_traits!(const);
293#[cfg(not(feature = "const-trait"))]
294define_traits!();