From d87d860cc8019ff6b9a71ca1d3dad0a251d9cd01 Mon Sep 17 00:00:00 2001 From: MildlyMeticulous Date: Sun, 9 Aug 2026 15:47:16 +0100 Subject: [PATCH] codec: optimize buffer reserve for `LengthDelimitedCodec::encode` (#8333) The reservation used `n`, the length after `length_adjustment` has been applied, but the encoder goes on to write `length_field_len` bytes of header plus `data.len()` bytes of payload. A positive `length_adjustment` therefore under-reserved by exactly the adjustment on every frame, and a negative one over-reserved, so the reservation did not match the write in either of the adjusted configurations shown in the module docs. --- tokio-util/src/codec/length_delimited.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index 8a7efbbdc..abc6461b5 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -631,8 +631,8 @@ impl Encoder for LengthDelimitedCodec { })?; // Reserve capacity in the destination buffer to fit the frame and - // length field (plus adjustment). - dst.reserve(self.builder.length_field_len + n); + // length field. + dst.reserve(self.builder.length_field_len + data.len()); if self.builder.length_field_is_big_endian { dst.put_uint(n as u64, self.builder.length_field_len);