fix: BytesMut only reuse if src has remaining (#803)

Signed-off-by: discord9 <[email protected]>
This commit is contained in:
discord9
2025-11-14 10:52:50 +01:00
committed by GitHub
parent 7ce330f519
commit 60cbb776f2
2 changed files with 14 additions and 2 deletions
+5 -2
View File
@@ -1202,8 +1202,11 @@ unsafe impl BufMut for BytesMut {
where
Self: Sized,
{
// When capacity is zero, try reusing allocation of `src`.
if self.capacity() == 0 {
if !src.has_remaining() {
// prevent calling `copy_to_bytes`->`put`->`copy_to_bytes` infintely when src is empty
return;
} else if self.capacity() == 0 {
// When capacity is zero, try reusing allocation of `src`.
let src_copy = src.copy_to_bytes(src.remaining());
drop(src);
match src_copy.try_into_mut() {
+9
View File
@@ -273,3 +273,12 @@ fn copy_from_slice_panics_if_different_length_2() {
let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), 3) };
slice.copy_from_slice(b"abcd");
}
/// Test if with zero capacity BytesMut does not infinitely recurse in put from Buf
#[test]
fn test_bytes_mut_reuse() {
let mut buf = BytesMut::new();
buf.put(&[] as &[u8]);
let mut buf = BytesMut::new();
buf.put(&[1u8, 2, 3] as &[u8]);
}