bytes icon indicating copy to clipboard operation
bytes copied to clipboard

Consider an unsplit method for Bytes

Open eloff opened this issue 3 years ago • 2 comments

I was looking for a way to join two contiguous Bytes into one, but there isn't such a thing.

It's common in parsing code to read multiple logical messages into a single BytesMut, split them off into individual Bytes for processing, but then it if they need to be written somewhere it can be advantageous to recombine them, if possible, so there are fewer syscalls to write. It's also possible to just use writev, but that typically involves an allocation for the iovec array and not all platforms support writev, and it's not an option if you're using a TLS wrapper around the stream. Using writev also requires much more code.

I think it is possible to do this safely:

impl Bytes {
    pub fn unsplit(self, other: Self) -> (Option<Self>, Option<Self>) {
        if is_contiguous(&self, &other) {
            return Some(merge(self, other)), None
        }
       (Some(self), Some(other))
    }
}

Does this seem like a worthwhile addition to the library?

eloff avatar Jul 05 '21 15:07 eloff

I needed this in more than one place as it turns out, so I implemented it using unsafe. Feel free to use any of this code in the bytes library, and relicense as required.

https://gist.github.com/eloff/6e0c236ae6388744a7d5b76a5e0e9b6c

eloff avatar Aug 02 '21 14:08 eloff

Looks like duplicate of #287

xonatius avatar Dec 10 '23 05:12 xonatius