futures_util/io/
read_to_string.rs

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::string::String;
8use std::vec::Vec;
9use 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"]
14pub 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
21impl<R: ?Sized + Unpin> Unpin for ReadToString<'_, R> {}
22
23impl<'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 = buf.len();
26        Self { reader, bytes: mem::take(buf).into_bytes(), buf, start_len }
27    }
28}
29
30fn 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 = 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(io::ErrorKind::InvalidData, "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(unsafe { buf.as_mut_vec() }, bytes);
46        Poll::Ready(ret)
47    }
48}
49
50impl<A> Future for ReadToString<'_, A>
51where
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, buf, bytes, start_len } = &mut *self;
58        read_to_string_internal(Pin::new(reader), cx, buf, bytes, *start_len)
59    }
60}