1use crate::io::util::vec_with_initialized::{into_read_buf_parts, VecU8, VecWithInitialized};
2use crate::io::{AsyncRead, ReadBuf};
34use pin_project_lite::pin_project;
5use std::future::Future;
6use std::io;
7use std::marker::PhantomPinned;
8use std::mem::{self, MaybeUninit};
9use std::pin::Pin;
10use std::task::{ready, Context, Poll};
1112pin_project! {
13#[derive(Debug)]
14 #[must_use = "futures do nothing unless you `.await` or poll them"]
15pub struct ReadToEnd<'a, R: ?Sized> {
16 reader: &'a mut R,
17 buf: VecWithInitialized<&'a mut Vec<u8>>,
18// The number of bytes appended to buf. This can be less than buf.len() if
19 // the buffer was not empty when the operation was started.
20read: usize,
21// Make this future `!Unpin` for compatibility with async trait methods.
22#[pin]
23_pin: PhantomPinned,
24 }
25}
2627pub(crate) fn read_to_end<'a, R>(reader: &'a mut R, buffer: &'a mut Vec<u8>) -> ReadToEnd<'a, R>
28where
29R: AsyncRead + Unpin + ?Sized,
30{
31 ReadToEnd {
32 reader,
33 buf: VecWithInitialized::new(buffer),
34 read: 0,
35 _pin: PhantomPinned,
36 }
37}
3839pub(super) fn read_to_end_internal<V: VecU8, R: AsyncRead + ?Sized>(
40 buf: &mut VecWithInitialized<V>,
41mut reader: Pin<&mut R>,
42 num_read: &mut usize,
43 cx: &mut Context<'_>,
44) -> Poll<io::Result<usize>> {
45loop {
46let ret = ready!(poll_read_to_end(buf, reader.as_mut(), cx));
47match ret {
48Err(err) => return Poll::Ready(Err(err)),
49Ok(0) => return Poll::Ready(Ok(mem::replace(num_read, 0))),
50Ok(num) => {
51*num_read += num;
52 }
53 }
54 }
55}
5657/// Tries to read from the provided [`AsyncRead`].
58///
59/// The length of the buffer is increased by the number of bytes read.
60fn poll_read_to_end<V: VecU8, R: AsyncRead + ?Sized>(
61 buf: &mut VecWithInitialized<V>,
62 read: Pin<&mut R>,
63 cx: &mut Context<'_>,
64) -> Poll<io::Result<usize>> {
65// This uses an adaptive system to extend the vector when it fills. We want to
66 // avoid paying to allocate and zero a huge chunk of memory if the reader only
67 // has 4 bytes while still making large reads if the reader does have a ton
68 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
69 // time is 4,500 times (!) slower than this if the reader has a very small
70 // amount of data to return. When the vector is full with its starting
71 // capacity, we first try to read into a small buffer to see if we reached
72 // an EOF. This only happens when the starting capacity is >= NUM_BYTES, since
73 // we allocate at least NUM_BYTES each time. This avoids the unnecessary
74 // allocation that we attempt before reading into the vector.
7576const NUM_BYTES: usize = 32;
77let try_small_read = buf.try_small_read_first(NUM_BYTES);
7879// Get a ReadBuf into the vector.
80let mut read_buf;
81let poll_result;
8283let n = if try_small_read {
84// Read some bytes using a small read.
85let mut small_buf: [MaybeUninit<u8>; NUM_BYTES] = [MaybeUninit::uninit(); NUM_BYTES];
86let mut small_read_buf = ReadBuf::uninit(&mut small_buf);
87 poll_result = read.poll_read(cx, &mut small_read_buf);
88let to_write = small_read_buf.filled();
8990// Ensure we have enough space to fill our vector with what we read.
91read_buf = buf.get_read_buf();
92if to_write.len() > read_buf.remaining() {
93 buf.reserve(NUM_BYTES);
94 read_buf = buf.get_read_buf();
95 }
96 read_buf.put_slice(to_write);
9798 to_write.len()
99 } else {
100// Ensure we have enough space for reading.
101buf.reserve(NUM_BYTES);
102 read_buf = buf.get_read_buf();
103104// Read data directly into vector.
105let filled_before = read_buf.filled().len();
106 poll_result = read.poll_read(cx, &mut read_buf);
107108// Compute the number of bytes read.
109read_buf.filled().len() - filled_before
110 };
111112// Update the length of the vector using the result of poll_read.
113let read_buf_parts = into_read_buf_parts(read_buf);
114 buf.apply_read_buf(read_buf_parts);
115116match poll_result {
117 Poll::Pending => {
118// In this case, nothing should have been read. However we still
119 // update the vector in case the poll_read call initialized parts of
120 // the vector's unused capacity.
121debug_assert_eq!(n, 0);
122 Poll::Pending
123 }
124 Poll::Ready(Err(err)) => {
125debug_assert_eq!(n, 0);
126 Poll::Ready(Err(err))
127 }
128 Poll::Ready(Ok(())) => Poll::Ready(Ok(n)),
129 }
130}
131132impl<A> Future for ReadToEnd<'_, A>
133where
134A: AsyncRead + ?Sized + Unpin,
135{
136type Output = io::Result<usize>;
137138fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
139let me = self.project();
140141 read_to_end_internal(me.buf, Pin::new(*me.reader), me.read, cx)
142 }
143}