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