Reputation: 43
I want to convert a 1D slice [f64] into a 2D slice [[f64; 2], i.e. [x0, y0, x1, y1, ...]
-> [[x0, y0], [x1, y1], ...]
.
My current solution uses unsafe code:
let points1d: &[f64] = &[0.0, 1.0, 2.0, 3.0];
if points1d.len() % 2 != 0 {
panic!("Bad slice");
}
let points2d: &[[f64; 2]] = unsafe { std::mem::transmute::<&[f64], &[[f64; 2]]>(points1d) };
I tried searching, but had no luck with my keywords (change dimensionality/pitch of arrays, reinterpret cast, convert slice). Thus, is there a safer, preferably equally efficient, way to do this?
Upvotes: 4
Views: 195
Reputation: 71005
The best way is to use the bytemuck
crate. This is equally efficient (it uses the same code under the hood).
let points1d: &[f64] = &[0.0, 1.0, 2.0, 3.0];
let points2d: &[[f64; 2]] = bytemuck::cast_slice(points1d);
Upvotes: 3