bytes
bytes copied to clipboard
Consider an unsplit method for Bytes
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?
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
Looks like duplicate of #287