Flatten Vec of arrays

I see this was discussed with tuples here: Flattening a vector of tuples

And leads to the following which works playground

fn flatten(data: &[[f32;3]]) -> &[f32] {
    use std::mem::transmute;
    use std::slice::from_raw_parts;
    unsafe {
        transmute( from_raw_parts(data.as_ptr(), data.len() * 3) )
    }
}

fn main() {
    let foo:Vec<[f32;3]> = vec![[1.0;3], [2.0;3]];    
    println!("{:?}", foo);
    
    println!("{:?}", flatten(&foo));
}

Is this implemented in a popular or standard library somewhere, or can I somehow impl Flatten for a Vec<[T;3]> where T: Float (from num crate)?

Oh sweet heavens, a customer!

https://docs.rs/slice-of-array

13 Likes

I started a PR for exactly this (thanks, const generics!):

But then aborted it on push-back. I guess I should go back to it…

Are you sure you need the transmute there?

1 Like

Nope, just copy/pasted/adjusted from the other forum post :wink:

Copy/pasting a bit more, from @ExpHP’s crate (which I’ll probably add as a dependency…), leads to this - without transmute: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b182fbe8af88963f0ff70f650cbcf41c