In Rust, I have a square, multidimensional array with a const generic size:
fn generate_array<const N: usize>() -> [[u32; N]; N] {
// ...
}
I want to pass this array to a library that takes a one-dimensional array:
fn library_function(width: usize, height: usize, data: &[u32]);
My array doesn't coerce to &[u32]
so I can't just pass a reference. I know this should be a trivial conversion, but I couldn't find an idiomatic way of doing it. From this post, I created a function to construct the slice from a raw pointer, but I am not sure if there are certain types where this is invalid.
const fn as_flat_slice<const N: usize, T>(arr: &[[T; N]; N]) -> &[T] {
unsafe {
std::slice::from_raw_parts(arr.as_ptr() as *const _, N * N)
}
}
Is there a non-unsafe
way to quickly perform this conversion?