Copying the content from a buffer to another taking in consideration an offset

What is the most common/efficient way of copying the content from a buffer to another taking in consideration an offset in Rust?

E.g:

let buf = vec![0u8; 5];
let content = vec![1, 2];
let start_at = 1;

// Fictitious method copy
buf.copy(content, start_at);

println!("Buffer: {:?}", buf);
// Buffer: [0, 1, 2, 0, 0]

I've looked over Vec documentation but didn't found anything like that

Maybe use slice::copy_from_slice. Example copied from the doc:

let src = [1, 2, 3, 4];
let mut dst = [0, 0];

// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.copy_from_slice(&src[2..]);
1 Like

This is useful, but idk if it fits my purpose.

I'm exchanging packets back and forth between tcp client and server. The first 64 bytes of the message are used for header. The content of the header may varies in size in this range.
In the server side I'll go through the header of the message looking for the first nullbyte with indicates the length of it, so I can read it peacefully.

Ideally in the client I'll create a fixed size vec, fill it with 64 nullbytes and copy the actual content to it, leaving the rest of null bytes behind.

copy_from_slice requires both vecs to be the same size, which is something that I cannot guarantee.

You can copy into a subslice:

let mut dst = vec![0u8; 2];
let src = vec![1u8];
dst[..src.len()].copy_from_slice(&src);
println!("{:?}", dst); // shows [1, 0]

Playground

3 Likes

It solves the problem.

Thank you so much

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.