Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

buffer

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?

like image 965
stu Avatar asked Oct 21 '25 04:10

stu


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:

  • How to idiomatically copy a slice?
  • How do you copy between arrays of different sizes in Rust?
  • How can I write data from a slice to the same slice?
  • How to operate on 2 mutable slices of a Rust array?
  • How do I create two new mutable slices from one slice?

without using unsafe

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

like image 183
Shepmaster Avatar answered Oct 23 '25 00:10

Shepmaster