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 >

Thanks

something like this:
Playground

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();
vec.extend_from_slice(b"i3-ipc");
vec.extend_from_slice(&len.to_ne_bytes());
vec.extend_from_slice(&msg);

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

std::mem::transmute?

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

3 Likes

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|

isn't

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.