1 | use futures_core::future::Future; |
2 | use futures_core::task::{Context, Poll}; |
3 | use futures_io::AsyncBufRead; |
4 | use std::io; |
5 | use std::pin::Pin; |
6 | use std::slice; |
7 | |
8 | /// Future for the [`fill_buf`](super::AsyncBufReadExt::fill_buf) method. |
9 | #[derive (Debug)] |
10 | #[must_use = "futures do nothing unless you `.await` or poll them" ] |
11 | pub struct FillBuf<'a, R: ?Sized> { |
12 | reader: Option<&'a mut R>, |
13 | } |
14 | |
15 | impl<R: ?Sized> Unpin for FillBuf<'_, R> {} |
16 | |
17 | impl<'a, R: AsyncBufRead + ?Sized + Unpin> FillBuf<'a, R> { |
18 | pub(super) fn new(reader: &'a mut R) -> Self { |
19 | Self { reader: Some(reader) } |
20 | } |
21 | } |
22 | |
23 | impl<'a, R> Future for FillBuf<'a, R> |
24 | where |
25 | R: AsyncBufRead + ?Sized + Unpin, |
26 | { |
27 | type Output = io::Result<&'a [u8]>; |
28 | |
29 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
30 | let this: &mut FillBuf<'_, R> = &mut *self; |
31 | let reader: &mut R = this.reader.take().expect(msg:"Polled FillBuf after completion" ); |
32 | |
33 | match Pin::new(&mut *reader).poll_fill_buf(cx) { |
34 | Poll::Ready(Ok(slice: &[u8])) => { |
35 | // With polonius it is possible to remove this lifetime transmutation and just have |
36 | // the correct lifetime of the reference inferred based on which branch is taken |
37 | let slice: &'a [u8] = unsafe { slice::from_raw_parts(data:slice.as_ptr(), slice.len()) }; |
38 | Poll::Ready(Ok(slice)) |
39 | } |
40 | Poll::Ready(Err(err: Error)) => Poll::Ready(Err(err)), |
41 | Poll::Pending => { |
42 | this.reader = Some(reader); |
43 | Poll::Pending |
44 | } |
45 | } |
46 | } |
47 | } |
48 | |