• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use super::read_to_end::read_to_end_internal;
2 use futures_core::ready;
3 use futures_core::future::Future;
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> {
new(reader: &'a mut R, buf: &'a mut String) -> Self23     pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self {
24         let start_len = buf.len();
25         Self {
26             reader,
27             bytes: mem::replace(buf, String::new()).into_bytes(),
28             buf,
29             start_len,
30         }
31     }
32 }
33 
read_to_string_internal<R: AsyncRead + ?Sized>( reader: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut String, bytes: &mut Vec<u8>, start_len: usize, ) -> Poll<io::Result<usize>>34 fn read_to_string_internal<R: AsyncRead + ?Sized>(
35     reader: Pin<&mut R>,
36     cx: &mut Context<'_>,
37     buf: &mut String,
38     bytes: &mut Vec<u8>,
39     start_len: usize,
40 ) -> Poll<io::Result<usize>> {
41     let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len));
42     if str::from_utf8(bytes).is_err() {
43         Poll::Ready(ret.and_then(|_| {
44             Err(io::Error::new(
45                 io::ErrorKind::InvalidData,
46                 "stream did not contain valid UTF-8",
47             ))
48         }))
49     } else {
50         debug_assert!(buf.is_empty());
51         // Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`.
52         mem::swap(unsafe { buf.as_mut_vec() }, bytes);
53         Poll::Ready(ret)
54     }
55 }
56 
57 impl<A> Future for ReadToString<'_, A>
58 where
59     A: AsyncRead + ?Sized + Unpin,
60 {
61     type Output = io::Result<usize>;
62 
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>63     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
64         let Self { reader, buf, bytes, start_len } = &mut *self;
65         read_to_string_internal(Pin::new(reader), cx, buf, bytes, *start_len)
66     }
67 }
68