From 869c3b46ac9a117c2d03902ff9e7f71bccf8ea6f Mon Sep 17 00:00:00 2001 From: Brad Dunbar Date: Sat, 2 Mar 2024 09:43:49 -0500 Subject: [PATCH 1/3] Remove redundant reserve call. 1. put_u8 calls put_slice 2. BytesMut::put_slice calls BytesMut::extend_from_slice 3. BytesMut::extend_from_slice immediately calls reserve --- src/bytes_mut.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/bytes_mut.rs b/src/bytes_mut.rs index 220bdb005..aec83f198 100644 --- a/src/bytes_mut.rs +++ b/src/bytes_mut.rs @@ -1285,7 +1285,6 @@ impl Extend for BytesMut { // 1. If self.kind() == KIND_VEC, use Vec::extend // 2. Make `reserve` inline-able for b in iter { - self.reserve(1); self.put_u8(b); } } From 0211037ad7e05b66580d4328b55c841a632f5911 Mon Sep 17 00:00:00 2001 From: Brad Dunbar Date: Sat, 2 Mar 2024 09:47:30 -0500 Subject: [PATCH 2/3] remove inline-able todo reserve is already inline-able --- src/bytes_mut.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/bytes_mut.rs b/src/bytes_mut.rs index aec83f198..2568975de 100644 --- a/src/bytes_mut.rs +++ b/src/bytes_mut.rs @@ -1283,7 +1283,6 @@ impl Extend for BytesMut { // TODO: optimize // 1. If self.kind() == KIND_VEC, use Vec::extend - // 2. Make `reserve` inline-able for b in iter { self.put_u8(b); } From 76dae7b880c52384d6a3edb364f1375b45a9274f Mon Sep 17 00:00:00 2001 From: Brad Dunbar Date: Sun, 3 Mar 2024 17:43:41 -0500 Subject: [PATCH 3/3] add a test for extending past lower limit For https://github.com/tokio-rs/bytes/pull/674#pullrequestreview-1913035700 --- tests/test_bytes.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/test_bytes.rs b/tests/test_bytes.rs index 76adfdbf4..e3820d76e 100644 --- a/tests/test_bytes.rs +++ b/tests/test_bytes.rs @@ -598,6 +598,28 @@ fn extend_mut_from_bytes() { assert_eq!(*bytes, LONG[..]); } +#[test] +fn extend_past_lower_limit_of_size_hint() { + // See https://github.com/tokio-rs/bytes/pull/674#pullrequestreview-1913035700 + struct Iter(I); + + impl> Iterator for Iter { + type Item = u8; + + fn next(&mut self) -> Option { + self.0.next() + } + + fn size_hint(&self) -> (usize, Option) { + (5, None) + } + } + + let mut bytes = BytesMut::with_capacity(5); + bytes.extend(Iter(std::iter::repeat(0).take(10))); + assert_eq!(bytes.len(), 10); +} + #[test] fn extend_mut_without_size_hint() { let mut bytes = BytesMut::with_capacity(0);