1use super::read_to_end::read_to_end_internal;
2use futures_core::future::Future;
3use futures_core::ready;
4use futures_core::task::{Context, Poll};
5use futures_io::AsyncRead;
6use std::pin::Pin;
7use std::vec::Vec;
8use 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"]
13pub 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
20impl<R: ?Sized + Unpin> Unpin for ReadToString<'_, R> {}
21
22impl<'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: usize = buf.len();
25 Self { reader, bytes: mem::take(dest:buf).into_bytes(), buf, start_len }
26 }
27}
28
29fn 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: Result = 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(kind:io::ErrorKind::InvalidData, error:"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(x:unsafe { buf.as_mut_vec() }, y:bytes);
45 Poll::Ready(ret)
46 }
47}
48
49impl<A> Future for ReadToString<'_, A>
50where
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: &mut &mut A, buf: &mut &mut String, bytes: &mut Vec, start_len: &mut usize } = &mut *self;
57 read_to_string_internal(reader:Pin::new(pointer:reader), cx, buf, bytes, *start_len)
58 }
59}
60