What is the proper way to convert a &[u8] into &[u32]?


Say I have a piece of raw memory allocated by some extern lib (e.g., libpcap or libpnet), which is returned as &[u8]. The actual data in the buffer is for example u32. The ideal way to use this piece of memory is

let raw_data:&[u8]=...  //fetch a borrow from some external for example cap.next(), where cap is a capture dev
let u32_data=unsafe{std::slice::from_raw_parts(raw_data.as_ptr() as *const u32, data.len()/4)};

However, cargo clippy complains about the alignment problem: u32 data requires more alignments.

In this condition, I can only call a memcpy:

let mut u32_data=vec![0_u32; raw_data.len()/4];
let mut u8_ref=unsafe{std::slice::from_raw_partsu32_data.as_mut_ptr() as *mut u8, u8_data.len())};
std::slice::copy_from_slice(u8_data, raw_data);

which has some performance overhead.

So is there a proper way to above things?


You can use <[u8]>::align_to::<u32>.