Skip to content

Commit 4d89adc

Browse files
committed
fix(body): set an internal max to reserve in to_bytes
Previously, `to_bytes` would reserve extra space if after two chunks, there was more remaining. It used to reserve however much space the peer advertized. This changes now only reserves up to ~16kb. This way, a slow message with a big body doesn't reserve so much memory, until the data has actually been received. The existing warning to check for a length before calling the function is still the best approach.
1 parent 031425f commit 4d89adc

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/body/to_bytes.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,13 @@ where
6363
return Ok(first.copy_to_bytes(first.remaining()));
6464
};
6565

66+
// Don't pre-emptively reserve *too* much.
67+
let rest = (body.size_hint().lower() as usize).min(1024 * 16);
68+
let cap = first
69+
.remaining()
70+
.saturating_add(second.remaining())
71+
.saturating_add(rest);
6672
// With more than 1 buf, we gotta flatten into a Vec first.
67-
let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize;
6873
let mut vec = Vec::with_capacity(cap);
6974
vec.put(first);
7075
vec.put(second);

0 commit comments

Comments
 (0)