#Idiomatic way to init u8 array from a smaller u8 array

4 messages · Page 1 of 1 (latest)

heavy sapphire
#

Hello, I am trying to init an u8 array from a smaller u8 array,
I writing a client for a protocol where there is a header and parameters or values, i need to put everything together in an arrat to write it to the server.Values are u8 and the header is an u8 array like in the code below:

const HEADER: [u8;6] = *b"HEADER";

let value1: u8 = 0;
let value2: u8 = 1;


// this code don't work but is there a way to do this?
let data: [u8;8] = [HEADER, value1, value2]

I could do a for loop over the header and fill the other array but i think it isnt the optimal way so is there a better way?

lilac berry
#

The most efficient way would probably to create the destination array with MaybeUninit and then copy_from_slice the elements over. You can turn your individual values into single-element arrays and then slices so that you can throw them all into the same loop.

But I wouldn't do that unless absolutely necessary. Just initialize it with zeroes and then copy_from_slice.

Also when working with streams of u8, it's usually a good idea to use the Read and Write traits so that you don't copy things more than you need to. You're copying these into an array that gets copied again into the server, when you could just copy them once.

heavy sapphire
#

Ok, Thank you very much, im going to use copy_from_slice, as i said im working on a client/library and creating an Request struct instance ,converting it to bytes and then sending it to the server because I think it is more clean and i can use it in differents contexts, like sending a request in tcp or udp but i don't know if i should prioritize speed or clarity do you know what is the best?

lilac berry
#

Read and Write is the idiomatic way to deal with network data. For example, to create a Read from your stuff:

use std::io::Read;
HEADER.chain(&[value1]).chain(&[value2])