| 1 | use super::read_to_end::read_to_end_internal; |
| 2 | use futures_core::future::Future; |
| 3 | use futures_core::ready; |
| 4 | use futures_core::task::{Context, Poll}; |
| 5 | use futures_io::AsyncRead; |
| 6 | use std::pin::Pin; |
| 7 | use std::string::String; |
| 8 | use std::vec::Vec; |
| 9 | use std::{io, mem, str}; |
| 10 | |
| 11 | /// Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method. |
| 12 | #[derive (Debug)] |
| 13 | #[must_use = "futures do nothing unless you `.await` or poll them" ] |
| 14 | pub struct ReadToString<'a, R: ?Sized> { |
| 15 | reader: &'a mut R, |
| 16 | buf: &'a mut String, |
| 17 | bytes: Vec<u8>, |
| 18 | start_len: usize, |
| 19 | } |
| 20 | |
| 21 | impl<R: ?Sized + Unpin> Unpin for ReadToString<'_, R> {} |
| 22 | |
| 23 | impl<'a, R: AsyncRead + ?Sized + Unpin> ReadToString<'a, R> { |
| 24 | pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self { |
| 25 | let start_len: usize = buf.len(); |
| 26 | Self { reader, bytes: mem::take(dest:buf).into_bytes(), buf, start_len } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | fn read_to_string_internal<R: AsyncRead + ?Sized>( |
| 31 | reader: Pin<&mut R>, |
| 32 | cx: &mut Context<'_>, |
| 33 | buf: &mut String, |
| 34 | bytes: &mut Vec<u8>, |
| 35 | start_len: usize, |
| 36 | ) -> Poll<io::Result<usize>> { |
| 37 | let ret: Result = ready!(read_to_end_internal(reader, cx, bytes, start_len)); |
| 38 | if str::from_utf8(bytes).is_err() { |
| 39 | Poll::Ready(ret.and_then(|_| { |
| 40 | Err(io::Error::new(kind:io::ErrorKind::InvalidData, error:"stream did not contain valid UTF-8" )) |
| 41 | })) |
| 42 | } else { |
| 43 | debug_assert!(buf.is_empty()); |
| 44 | // Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`. |
| 45 | mem::swap(x:unsafe { buf.as_mut_vec() }, y:bytes); |
| 46 | Poll::Ready(ret) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl<A> Future for ReadToString<'_, A> |
| 51 | where |
| 52 | A: AsyncRead + ?Sized + Unpin, |
| 53 | { |
| 54 | type Output = io::Result<usize>; |
| 55 | |
| 56 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 57 | let Self { reader: &mut &mut A, buf: &mut &mut String, bytes: &mut Vec, start_len: &mut usize } = &mut *self; |
| 58 | read_to_string_internal(reader:Pin::new(pointer:reader), cx, buf, bytes, *start_len) |
| 59 | } |
| 60 | } |
| 61 | |