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::replace(buf, String::new()).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 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 debug_assert_eq!(*read, 0);
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
50 impl<R: AsyncBufRead + ?Sized + Unpin> Future for ReadLine<'_, R> {
51 type Output = io::Result<usize>;
52
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>53 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
54 let Self { reader, buf, bytes, read } = &mut *self;
55 read_line_internal(Pin::new(reader), cx, buf, bytes, read)
56 }
57 }
58