Search code examples
rustrust-tokio

How to move a range of elements from BytesMut?


I have a method that takes a mutable instance of BytesMut. I want to move chunks of it into other instances of BytesMut but am not sure about the syntax to do so. Are there any examples out there?


Solution

  • You could use the range operator on the original buf to move things around or split_off based on some offset value. For example:

    use bytes::{BufMut, BytesMut};
    
    fn main() {
        let mut buf = BytesMut::with_capacity(64);
        let mut buf_to = BytesMut::with_capacity(64);
    
        buf.put_u8(b't');
        buf.put_u8(b'e');
        buf.put_u8(b's');
        buf.put_u8(b't');
    
        // move last 2 elements
        buf_to.put(&buf[2..]);
        println!("{:#?}", buf_to); // b"st"
    
        // You can also split_off the original value
        let mut another_buf = buf.split_off(2);
        println!("{:#?}", another_buf); // b"st"
        println!("{:#?}", buf); // b"te"
    }