'How do I insert a dynamic byte string into a vector?

I need to create packet to send to the server. For this purpose I use vector with byteorder crate. When I try to append string, Rust compiler tells I use unsafe function and give me an error.

use byteorder::{LittleEndian, WriteBytesExt};

fn main () {
    let login = "test";
    let packet_length = 30 + (login.len() as i16);

    let mut packet = Vec::new();
    packet.write_u8(0x00);
    packet.write_i16::<LittleEndian>(packet_length);
    packet.append(&mut Vec::from(String::from("game name ").as_bytes_mut()));

    // ... rest code
}

The error is:

packet.append(&mut Vec::from(String::from("game name ").as_bytes_mut()));
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function

This is playground to reproduce: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=381c6d14660d47beaece15d068b3dc6a

What is the correct way to insert some string as bytes into vector ?



Solution 1:[1]

You can use .extend() on the Vec and pass in the bytes representation of the String:

use byteorder::{LittleEndian, WriteBytesExt};

fn main() {
    let login = "test";
    let packet_length = 30 + (login.len() as i16);
    let mut packet = Vec::new();
    packet.write_u8(0x00);
    packet.write_i16::<LittleEndian>(packet_length);
    let string = String::from("game name ");
    packet.extend(string.as_bytes());
}

Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dogbert