unaligned access support
Opened this issue · 4 comments
Is there any interest in providing something that could, for example, take an unaligned [u8] slice and convert it to a u32?
Hm. You can already do this by changing &[u8]
to &[u8; 4]
, dereferencing that to [u8; 4]
, and then casting to u32
.
It's not an easy single step thing though. We might be able to make an improvement here.
Here is something that should work for all Pod
types:
fn read_unaligned<T: Pod>(bytes: &[u8]) -> T {
let mut val = T::zeroed();
bytes_of_mut(&mut val).copy_from_slice(bytes);
val
}
I kinda like it, but I wish that the read_unaligned
could take an array of bytes and then have the array length be determined by the size_of::<T>()
. I didn't actually try it in the playground, but i suspect that it won't work because I think that currently const generics still can't use another generic type to determine a const.
It could be something nice for a lot of functions actually (eg bytes_of
returning an array reference instead of a slice).
Unfortunately it currently requires #![feature(generic_const_exprs)]