Skip to content

Commit 81550da

Browse files
Bryan Donlanseanmonstar
Bryan Donlan
authored andcommitted
BytesMut: Reuse buffer when data fully consumed via Buf
Closes #412
1 parent 90e7e65 commit 81550da

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/bytes_mut.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -559,9 +559,8 @@ impl BytesMut {
559559
unsafe {
560560
let (off, prev) = self.get_vec_pos();
561561

562-
// Only reuse space if we stand to gain at least capacity/2
563-
// bytes of space back
564-
if off >= additional && off >= (self.cap / 2) {
562+
// Only reuse space if we can satisfy the requested additional space.
563+
if self.capacity() - self.len() + off >= additional {
565564
// There's space - reuse it
566565
//
567566
// Just move the pointer back to the start after copying

tests/test_bytes.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -929,6 +929,22 @@ fn bytes_buf_mut_advance() {
929929
}
930930
}
931931

932+
#[test]
933+
fn bytes_buf_mut_reuse_when_fully_consumed() {
934+
use bytes::{Buf, BytesMut};
935+
let mut buf = BytesMut::new();
936+
buf.reserve(8192);
937+
buf.extend_from_slice(&[0u8; 100][..]);
938+
939+
let p = &buf[0] as *const u8;
940+
buf.advance(100);
941+
942+
buf.reserve(8192);
943+
buf.extend_from_slice(b" ");
944+
945+
assert_eq!(&buf[0] as *const u8, p);
946+
}
947+
932948
#[test]
933949
#[should_panic]
934950
fn bytes_reserve_overflow() {

0 commit comments

Comments
 (0)