Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make BytesMut::try_unsplit method public #746

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions src/bytes_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,8 @@ impl BytesMut {
}
}

/// Absorbs a `BytesMut` that was previously split off.
/// Absorbs a `BytesMut` that was previously split off if they are
/// contiguous, otherwise appends its bytes to this `BytesMut`.
///
/// If the two `BytesMut` objects were previously contiguous and not mutated
/// in a way that causes re-allocation i.e., if `other` was created by
Expand Down Expand Up @@ -990,7 +991,35 @@ impl BytesMut {
self.cap -= count;
}

fn try_unsplit(&mut self, other: BytesMut) -> Result<(), BytesMut> {
/// Absorbs a `BytesMut` that was previously split off.
///
/// If the two `BytesMut` objects were previously contiguous, i.e., if
/// `other` was created by calling `split_off` on this `BytesMut`, then
/// this is an `O(1)` operation that just decreases a reference
/// count and sets a few indices. Otherwise this method returns an error
/// containing the original `other`.
///
/// # Examples
///
/// ```
/// use bytes::BytesMut;
///
/// let mut buf = BytesMut::with_capacity(64);
/// buf.extend_from_slice(b"aaabbbcccddd");
///
/// let mut split_1 = buf.split_off(3);
/// let split_2 = split_1.split_off(3);
/// assert_eq!(b"aaa", &buf[..]);
/// assert_eq!(b"bbb", &split_1[..]);
/// assert_eq!(b"cccddd", &split_2[..]);
///
/// let split_2 = buf.try_unsplit(split_2).unwrap_err();
///
/// buf.try_unsplit(split_1).unwrap();
/// buf.try_unsplit(split_2).unwrap();
/// assert_eq!(b"aaabbbcccddd", &buf[..]);
/// ```
pub fn try_unsplit(&mut self, other: BytesMut) -> Result<(), BytesMut> {
if other.capacity() == 0 {
return Ok(());
}
Expand Down