1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::future::Future;
use std::io::{ErrorKind, Result};
use std::marker::PhantomPinned;
use std::mem::MaybeUninit;
use std::pin::Pin;
use std::slice;
use std::task::{Context, Poll};

use aliasable::AliasableMut;
use completion_core::CompletionFuture;
use completion_io::{AsyncRead, AsyncReadWith, ReadBuf};
use futures_core::ready;
use pin_project_lite::pin_project;

use super::extend_lifetime_mut;

pin_project! {
    /// Future for [`AsyncReadExt::read_to_end`](super::AsyncReadExt::read_to_end).
    pub struct ReadToEnd<'a, T>
    where
        T: AsyncRead,
        T: ?Sized,
    {
        // The current reading future.
        #[pin]
        fut: Option<<T as AsyncReadWith<'a>>::ReadFuture>,

        reader: AliasableMut<'a, T>,

        // The buffer the future reads to. It has to be boxed as the future also holds a reference
        // to it and Rust doesn't support shared locals. It holds a reference to the data in `buf`.
        read_buf: Box<Option<ReadBuf<'a>>>,

        // Although this type could in theory be `Unpin`, we want to be able to unbox `read_buf` in
        // the future without breaking changes.
        #[pin]
        _pinned: PhantomPinned,

        // The buffer that was passed into `read_to_end`.
        buf: &'a mut Vec<u8>,

        // The index in the buffer up to which it is initialized. This often will go beyond the
        // length of the buffer.
        initialized_to: usize,

        // The number of filled bytes at the start of the operation.
        initial_filled: usize,
    }
}

impl<'a, T: AsyncRead + ?Sized + 'a> ReadToEnd<'a, T> {
    pub(super) fn new(reader: &'a mut T, buf: &'a mut Vec<u8>) -> Self {
        let buf_len = buf.len();
        Self {
            fut: None,
            reader: AliasableMut::from_unique(reader),
            read_buf: Box::new(None),
            _pinned: PhantomPinned,
            buf,
            initialized_to: buf_len,
            initial_filled: buf_len,
        }
    }
}

impl<'a, T: AsyncRead + ?Sized + 'a> CompletionFuture for ReadToEnd<'a, T> {
    type Output = Result<usize>;

    unsafe fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();

        loop {
            if let Some(fut) = this.fut.as_mut().as_pin_mut() {
                let res = ready!(fut.poll(cx));
                this.fut.set(None);

                // There is no future, so we can create a mutable reference to `read_buf` without
                // aliasing.
                let read_buf = this.read_buf.take().unwrap();

                match res {
                    Ok(()) => {
                        let filled = read_buf.filled().len();
                        let initialized = read_buf.initialized().len();

                        drop(read_buf);

                        // No bytes were written to the buffer; we have reached EOF.
                        if filled == 0 {
                            return Poll::Ready(Ok(this.buf.len() - *this.initial_filled));
                        }

                        this.buf.set_len(this.buf.len() + filled);
                        *this.initialized_to = this.buf.len() + initialized;
                    }
                    Err(e) if e.kind() == ErrorKind::Interrupted => {}
                    Err(e) => return Poll::Ready(Err(e)),
                }
            }

            this.buf.reserve(32);

            // Set up the read buffer.
            **this.read_buf = Some(ReadBuf::uninit(slice::from_raw_parts_mut(
                this.buf.as_mut_ptr().add(this.buf.len()) as *mut MaybeUninit<u8>,
                this.buf.capacity() - this.buf.len(),
            )));
            let read_buf = (**this.read_buf).as_mut().unwrap();
            read_buf.assume_init(*this.initialized_to - this.buf.len());

            // Set the reading future.
            let reader = extend_lifetime_mut(&mut **this.reader);
            let read_buf = extend_lifetime_mut(read_buf);
            this.fut.as_mut().set(Some(reader.read(read_buf.as_mut())));
        }
    }
    unsafe fn poll_cancel(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        if let Some(fut) = self.project().fut.as_pin_mut() {
            fut.poll_cancel(cx)
        } else {
            Poll::Ready(())
        }
    }
}
impl<'a, T: AsyncRead + ?Sized + 'a> Future for ReadToEnd<'a, T>
where
    <T as AsyncReadWith<'a>>::ReadFuture: Future<Output = Result<()>>,
{
    type Output = Result<usize>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        unsafe { CompletionFuture::poll(self, cx) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::io::{Cursor, Error};

    use crate::future::block_on;

    use super::super::{
        test_utils::{poll_once, YieldingReader},
        AsyncReadExt,
    };

    #[test]
    fn no_yield() {
        let mut v = Vec::new();

        let mut cursor = Cursor::new(&[1, 2, 3, 4, 5]);
        assert_eq!(block_on(cursor.read_to_end(&mut v)).unwrap(), 5);
        assert_eq!(v, &[1, 2, 3, 4, 5]);

        let mut cursor = Cursor::new(&[8; 500]);
        assert_eq!(block_on(cursor.read_to_end(&mut v)).unwrap(), 500);
        assert_eq!(v.len(), 505);
        assert!(v.starts_with(&[1, 2, 3, 4, 5]));
        for &n in &v[5..] {
            assert_eq!(n, 8);
        }
    }

    #[test]
    fn yielding() {
        const BYTES: usize = 13;

        let mut v = Vec::new();

        let mut reader = YieldingReader::new((0..BYTES).map(|_| Ok([18_u8])));
        assert_eq!(block_on(reader.read_to_end(&mut v)).unwrap(), BYTES);
        assert_eq!(v, [18; BYTES]);
    }

    #[test]
    fn partial() {
        let mut v = Vec::new();

        let mut reader = YieldingReader::new((0..10).map(|_| [10, 11]).map(Ok));
        let fut = reader.read_to_end(&mut v);
        futures_lite::pin!(fut);
        assert!(poll_once(fut.as_mut()).is_none());
        assert!(poll_once(fut.as_mut()).is_none());
        assert_eq!(v, [10, 11]);
    }

    #[test]
    fn error() {
        let mut v = vec![1, 2, 3];

        let mut reader = YieldingReader::new(vec![
            Ok([4, 5]),
            Ok([6, 7]),
            Err(Error::new(ErrorKind::Other, "Some error")),
            Ok([8, 9]),
        ]);
        assert_eq!(
            block_on(reader.read_to_end(&mut v))
                .unwrap_err()
                .to_string(),
            "Some error"
        );
        assert_eq!(v, [1, 2, 3, 4, 5, 6, 7]);
    }

    #[test]
    fn ignore_interrupted() {
        let mut v = vec![1, 2, 3];

        let mut reader = YieldingReader::new(vec![
            Err(Error::from(ErrorKind::Interrupted)),
            Ok(&[4, 5][..]),
            Err(Error::from(ErrorKind::Interrupted)),
            Err(Error::from(ErrorKind::Interrupted)),
            Ok(&[6]),
            Err(Error::from(ErrorKind::Interrupted)),
            Ok(&[7, 8]),
        ]);
        assert_eq!(block_on(reader.read_to_end(&mut v)).unwrap(), 5);
        assert_eq!(v, [1, 2, 3, 4, 5, 6, 7, 8]);
    }
}