bytemuck icon indicating copy to clipboard operation
bytemuck copied to clipboard

unaligned access support

Open jrmuizel opened this issue 3 years ago • 4 comments

Is there any interest in providing something that could, for example, take an unaligned [u8] slice and convert it to a u32?

jrmuizel avatar Feb 24 '21 16:02 jrmuizel

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.

Lokathor avatar Feb 24 '21 16:02 Lokathor

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
}

a1phyr avatar Nov 19 '21 14:11 a1phyr

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.

Lokathor avatar Nov 21 '21 18:11 Lokathor

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)]

a1phyr avatar Nov 21 '21 19:11 a1phyr