Constructing byte arrays in Rust

Hello! I am trying to construct byte arrays. What is the best way to do it? The byte array will comprise of text, serialized u32 etc.
I am trying to implement i3 ipc protocol. So I would have to construct byte sequences of the form

i3-ipc < payload len > < msg type >


something like this:

fn main() {
    let body = "Hello";
    let message_type = 0;
    let message = format!("i3-ipc{}{}{}", body.len(), message_type, body); 
    let ready_to_send = message.as_bytes();
   println!("{:?}", ready_to_send);

You can make a vector and use extend_from_slice to append various slices of data.

let mut vec = Vec::new();

Thanks. But what is the best way to convert u32 to bytes as well (iLittleEndian , taking up 4 bytes)?


Your linked documentation says the byte should be in native endian order, so you would use u32::to_ne_bytes.


Oh, yes!
But there is an example given below, in the same article.

00000000 69 33 2d 69 70 63 04 00 00 00 00 00 00 00 65 78 |i3-ipc........ex|
00000010 69 74 |it|


04 00 00 00

sequence in LittleEndian, considering the message length is 4 here?

Yes, most computers are little endian, so native endian would be little endian on most computers.

Oh I got confused between native endian and network endian(which is big endian) :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.