Skip to content

Commit 8ed5677

Browse files
committed
In ready_chunks, reserve capacity based on size_hint
Reserving `ready_chunks` limit every time may be too expensive when the limit is high but only a few number of messages available. Now rely on `Stream::size_hint` to reserve the capacity. If underlying stream implements `size_hint`, this will work great. Otherwise `ready_chunk` will be somewhat less efficient. This is better alternative to #2657
1 parent 260f9e9 commit 8ed5677

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

futures-util/src/stream/stream/ready_chunks.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use futures_core::task::{Context, Poll};
66
#[cfg(feature = "sink")]
77
use futures_sink::Sink;
88
use pin_project_lite::pin_project;
9+
use std::cmp;
910

1011
pin_project! {
1112
/// Stream for the [`ready_chunks`](super::StreamExt::ready_chunks) method.
@@ -49,7 +50,11 @@ impl<St: Stream> Stream for ReadyChunks<St> {
4950
// the full one.
5051
Poll::Ready(Some(item)) => {
5152
if items.is_empty() {
52-
items.reserve(*this.cap);
53+
// Note we reserve capacity here, not when `items` is created,
54+
// because stream may know the remaining size,
55+
// but items might not be readily available.
56+
let size_hint = this.stream.as_mut().size_hint().0.wrapping_add(1);
57+
items.reserve(cmp::min(*this.cap, size_hint));
5358
}
5459
items.push(item);
5560
if items.len() >= *this.cap {

0 commit comments

Comments
 (0)