Skip to content

Commit 60cbb77

Browse files
authored
fix: BytesMut only reuse if src has remaining (#803)
Signed-off-by: discord9 <[email protected]>
1 parent 7ce330f commit 60cbb77

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/bytes_mut.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,8 +1202,11 @@ unsafe impl BufMut for BytesMut {
12021202
where
12031203
Self: Sized,
12041204
{
1205-
// When capacity is zero, try reusing allocation of `src`.
1206-
if self.capacity() == 0 {
1205+
if !src.has_remaining() {
1206+
// prevent calling `copy_to_bytes`->`put`->`copy_to_bytes` infintely when src is empty
1207+
return;
1208+
} else if self.capacity() == 0 {
1209+
// When capacity is zero, try reusing allocation of `src`.
12071210
let src_copy = src.copy_to_bytes(src.remaining());
12081211
drop(src);
12091212
match src_copy.try_into_mut() {

tests/test_buf_mut.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,3 +273,12 @@ fn copy_from_slice_panics_if_different_length_2() {
273273
let slice = unsafe { UninitSlice::from_raw_parts_mut(data.as_mut_ptr(), 3) };
274274
slice.copy_from_slice(b"abcd");
275275
}
276+
277+
/// Test if with zero capacity BytesMut does not infinitely recurse in put from Buf
278+
#[test]
279+
fn test_bytes_mut_reuse() {
280+
let mut buf = BytesMut::new();
281+
buf.put(&[] as &[u8]);
282+
let mut buf = BytesMut::new();
283+
buf.put(&[1u8, 2, 3] as &[u8]);
284+
}

0 commit comments

Comments
 (0)