Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely converting a 1D slice into a 2D slice

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?

like image 340
Christoph Schulz Avatar asked Oct 17 '25 06:10

Christoph Schulz


1 Answers

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);
like image 198
Chayim Friedman Avatar answered Oct 19 '25 20:10

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!