Expand description
Reshaping of arrays, by value, by reference and by mutable reference, all in const fn.
<[[T; N]]>::as_flattened() and
<[T]>::as_chunks() in the standard library convert to and from slices,
losing the length in the process. This crate converts between arrays of the same total length
instead, for example [[T; N]; M] into [T; N * M]:
use array_reshape::{Flatten, Rechunk, Unflatten};
let pairs = [[1, 2], [3, 4], [5, 6]];
let flat: &[u8; 6] = pairs.flatten_ref();
assert_eq!(flat, &[1, 2, 3, 4, 5, 6]);
let triples = pairs.rechunk_ref::<3, 2>();
assert_eq!(triples, &[[1, 2, 3], [4, 5, 6]]);
let pairs_again = flat.unflatten::<2, 3>();
assert_eq!(pairs_again, pairs);§const fn support
Trait methods can’t be called in const fn on stable Rust, which is why every conversion is
also available as a free const fn with the same name:
const FLAT: [u8; 4] = array_reshape::flatten([[1, 2], [3, 4]]);
assert_eq!(FLAT, [1, 2, 3, 4]);With the const-trait feature, which requires nightly Rust, Flatten, Rechunk and
Unflatten become const traits, so their methods can be called in const fn directly.
Crates calling them in const fn need to enable const_trait_impl feature themselves.
§Output length
Stable Rust doesn’t allow computing array lengths from generic constants yet (which would
require generic_const_exprs feature), so the length of the output is a separate generic
parameter, which is usually inferred from the context. The lengths are checked at compile
time, but since the check happens after monomorphization, it is only reported by
cargo build, not cargo check:
use array_reshape::Flatten;
let pairs = [[1, 2], [3, 4], [5, 6]];
let flat: &[u8; 5] = pairs.flatten_ref();The check also happens for code that is never executed, but is compiled, like match arms
that don’t match for a particular set of generic parameters. Convert the input into an array
of a concrete size in such cases first (for example with
<[T]>::as_array()).
Traits§
- Flatten
- Reshaping of
[[T; N]; M], see crate-level documentation for examples. - Rechunk
- Changing chunk size of
[[T; N]; M], see crate-level documentation for examples. - Unflatten
- Reshaping of
[T; K], see crate-level documentation for examples.
Functions§
- flatten
- Flatten
[[T; N]; M]into[T; K], whereK == N * M - flatten_
mut - Flatten
&mut [[T; N]; M]into&mut [T; K], whereK == N * M - flatten_
ref - Flatten
&[[T; N]; M]into&[T; K], whereK == N * M - rechunk
- Change chunk size of
[[T; A]; B]to get[[T; C]; D], whereA * B == C * D - rechunk_
mut - Change chunk size of
&mut [[T; A]; B]to get&mut [[T; C]; D], whereA * B == C * D - rechunk_
ref - Change chunk size of
&[[T; A]; B]to get&[[T; C]; D], whereA * B == C * D - unflatten
- Unflatten
[T; K]into[[T; N]; M], whereK == N * M - unflatten_
mut - Unflatten
&mut [T; K]into&mut [[T; N]; M], whereK == N * M - unflatten_
ref - Unflatten
&[T; K]into&[[T; N]; M], whereK == N * M