Unlikus
Unlikus

Reputation: 1858

Is flattening arrays by mem::transmute safe?

Is flattening an array like this safe for build in primitive types?

let a = [[0u32;4];4];
let b = std::mem::transmute::<[[u32;4];4], [u32; 16]>(a);

What are the conditions under this this is safe?

Upvotes: 3

Views: 409

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601679

Arrays are one of the few data structures with guaranteed memory layouts in Rust. The array [T; N] is guaranteed to be laid out as N consecutive instances of T in memory. Thus [[T; M]; N] is guaranteed to have the same memory layout as [T; M * N], and transmuting from one to the other is safe for any type T.

Upvotes: 9

Related Questions