• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use super::read_until::read_until_internal;
2 use futures_core::future::Future;
3 use futures_core::ready;
4 use futures_core::task::{Context, Poll};
5 use futures_io::AsyncBufRead;
6 use std::io;
7 use std::mem;
8 use std::pin::Pin;
9 use std::str;
10 
11 /// Future for the [`read_line`](super::AsyncBufReadExt::read_line) method.
12 #[derive(Debug)]
13 #[must_use = "futures do nothing unless you `.await` or poll them"]
14 pub struct ReadLine<'a, R: ?Sized> {
15     reader: &'a mut R,
16     buf: &'a mut String,
17     bytes: Vec<u8>,
18     read: usize,
19 }
20 
21 impl<R: ?Sized + Unpin> Unpin for ReadLine<'_, R> {}
22 
23 impl<'a, R: AsyncBufRead + ?Sized + Unpin> ReadLine<'a, R> {
new(reader: &'a mut R, buf: &'a mut String) -> Self24     pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self {
25         Self { reader, bytes: mem::take(buf).into_bytes(), buf, read: 0 }
26     }
27 }
28 
read_line_internal<R: AsyncBufRead + ?Sized>( reader: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut String, bytes: &mut Vec<u8>, read: &mut usize, ) -> Poll<io::Result<usize>>29 pub(super) fn read_line_internal<R: AsyncBufRead + ?Sized>(
30     reader: Pin<&mut R>,
31     cx: &mut Context<'_>,
32     buf: &mut String,
33     bytes: &mut Vec<u8>,
34     read: &mut usize,
35 ) -> Poll<io::Result<usize>> {
36     let ret = ready!(read_until_internal(reader, cx, b'\n', bytes, read));
37     if str::from_utf8(bytes).is_err() {
38         bytes.clear();
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         debug_assert_eq!(*read, 0);
45         // Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`.
46         mem::swap(unsafe { buf.as_mut_vec() }, bytes);
47         Poll::Ready(ret)
48     }
49 }
50 
51 impl<R: AsyncBufRead + ?Sized + Unpin> Future for ReadLine<'_, R> {
52     type Output = io::Result<usize>;
53 
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>54     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
55         let Self { reader, buf, bytes, read } = &mut *self;
56         read_line_internal(Pin::new(reader), cx, buf, bytes, read)
57     }
58 }
59