Safe way to cast &[u64;8] to &[u8;8]?

I'm looking for a safe way to cast the slice. Actually I don't mind if it has to do some copying. Luckly they are fixed size, so I can have an intermediate slice for the conversion.

However, how should I do it? Is there an easy way?

What conversion are you looking for here? Do you want the bytes of the first u64? Did you mean &[u8; 64]? Did you want the equivalent of as-cast-truncating the 8 values?


the same conversion as C++ when it does (uint8_t*)(uint64_pointer)

Sounds like you might be looking for

with copy it would be:

    let arr: &[u64; 8] = todo!();
    let bytes = arr[0].to_le_bytes();
    let bytes_ref: &[u8; 8] = &bytes;

In fact this code also not so bad:

    let bytes_ref: &[u8; 8] = unsafe { transmute(arr) };

requirements for alignment for u64 is more strict then for u8.

This might swap the bytes in BE platforms like POWERPC/SPARC which is supported by the Rust as a tier 3 target. To achieve consistent behavior with the C++ code OP mentioned which is inconsistent over values between platforms, use .to_ne_bytes() instead.

Also it's questionable why OP wants to take &[u64; 8] and ignore 7 trailing u64s.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.