2

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)
    }
}

(playground link)

Is there a non-unsafe way to quickly perform this conversion?

gfaster
  • 157
  • 2
  • 12
  • 1
    [`slice::flatten`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.flatten)? (currently unstable) – PitaJ Jun 28 '23 at 17:43

1 Answers1

1

On nightly, there is <[T]>::flatten().

On stable, there is nothing in the standard library, although there is crates [e.g. slice-of-array).

Anyhow, your code is sound.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77