Carson
Carson

Reputation: 3139

How to set a subarray in rust

Still new to rust, so sorry if a little bit of a basic question, but I can't find any good resource. I'm writing some ipc code, and I have the following snippet:

// Header format           | "magic string"          | msg len   | msg type id |
let mut header: [u8; 14] = [105, 51, 45, 105, 112, 99, 0, 0, 0, 0, 0, 0, 0, 0];

I want to set header [10..14] to the native byte order encoding of a 32bit message type. I also want to set header[6..10] to the message length (again native byte order 32 bit int).

So far I have tried:

Using slices: (cannot find a form that compiles)

header[10 .. 14] = msg_type.to_ne_bytes();

Some weird array design (cannot find a form that compiles)

[header[10], header[11], header[12], header[13]] = msg_type.to_ne_bytes();

Saving the result and writing it over. This works, but seems inelegant. If this is the right answer, I understand, it just feels wrong.

let res = msg_type.to_ne_bytes();
header[10] = res[0];
header[11] = res[1];
header[12] = res[2];
header[13] = res[3];

If there is also some way to do this with the array creation, I am happy to look into it. Thanks in advance!

P.S. this is a client for swaywm's ipc messaging if anyone is curious.

Upvotes: 5

Views: 5639

Answers (1)

creanion
creanion

Reputation: 2762

Using slices is the way to go. It's an array, so you get all the slice methods on the array as well.

We take your example header[10 .. 14] = msg_type.to_ne_bytes(); and turn it into this, which works:

header[10..14].copy_from_slice(&msg_type.to_ne_bytes());

Note that in a.copy_from_slice(b) you need to ensure that a and b have the same length, otherwise the method call panics.

(An alternative but very similar way would be to use the crate byteorder.)

Upvotes: 4

Related Questions