Vec to sized array

I am trying to convert a Vec<u8> (of a known size) to a [u8; 8]. I would like to do this without a for loop, and a mem::transmute complained about different sizes (likely due to vec being a thick pointer, and trying to transmute a &[u8] also does not work for the same reason). Is there any good way to do this? I remember doing something slimier to this a while ago (the work has since been lost).

you can use TryInto:

assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
7 Likes

transmute is extremely inappropriate for this. If you pass the Vec<u8> to transmute, you will be transmuting the 24-byte metadata with pointer and length information instead of the data stored in the Vec. If your array was 24 bytes long, then transmute would allow it, but you would get a completely unexpected result with the wrong data.

3 Likes

Of what size?

If you just want the first 8 bytes (or None if it's not long enough), then you're looking for first_chunk: https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.first_chunk

Is your problem solved?