How do I update a section of a Bytes/BytesMut?

Viewed 1178

I have a fixed size buffer in a Bytes struct, and I want to copy some data over the middle of it.

The only thing I can see at the moment would be to take a slice of the beginning, add what I want, and add the slice at the end, but I'm sure this will result in a large copy or two that I want to avoid, I simply need to update the middle of the buffer. Is there a simple way of doing that without using unsafe?

1 Answers

You don't mutate Bytes. The entire purpose of the struct is to represent a reference-counted immutable view of data. You will need to copy the data in some fashion. Perhaps you create a Vec<u8> or BytesMut from the data.

BytesMut implements AsMut<[u8]>, BorrowMut<[u8]> and DerefMut, so you can use any existing technique for modifying slices in-place. For example:

use bytes::BytesMut; // 0.5.4

fn main() {
    let mut b = BytesMut::new();
    b.extend_from_slice(b"a good time");

    let middle = &mut b[2..][..4];
    middle.copy_from_slice(b"cool");

    println!("{}", String::from_utf8_lossy(&b));
}

See also:

without using unsafe

Do not use unsafe for this problem. You will cause undefined behavior.

Related