Skip to content

Commit

Permalink
fix(body): set an internal max to reserve in to_bytes
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
seanmonstar committed Jan 12, 2023
1 parent 031425f commit 4d89adc
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/body/to_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,13 @@ where
return Ok(first.copy_to_bytes(first.remaining()));
};

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

0 comments on commit 4d89adc

Please sign in to comment.