1use super::read_until::read_until_internal;
2use futures_core::future::Future;
3use futures_core::ready;
4use futures_core::task::{Context, Poll};
5use futures_io::AsyncBufRead;
6use std::io;
7use std::mem;
8use std::pin::Pin;
9use 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"]
14pub struct ReadLine<'a, R: ?Sized> {
15 reader: &'a mut R,
16 buf: &'a mut String,
17 bytes: Vec<u8>,
18 read: usize,
19}
20
21impl<R: ?Sized + Unpin> Unpin for ReadLine<'_, R> {}
22
23impl<'a, R: AsyncBufRead + ?Sized + Unpin> ReadLine<'a, R> {
24 pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self {
25 Self { reader, bytes: mem::take(dest:buf).into_bytes(), buf, read: 0 }
26 }
27}
28
29pub(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: Result = 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(kind:io::ErrorKind::InvalidData, error:"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(x:unsafe { buf.as_mut_vec() }, y:bytes);
46 Poll::Ready(ret)
47 }
48}
49
50impl<R: AsyncBufRead + ?Sized + Unpin> Future for ReadLine<'_, R> {
51 type Output = io::Result<usize>;
52
53 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
54 let Self { reader: &mut &mut R, buf: &mut &mut String, bytes: &mut Vec, read: &mut usize } = &mut *self;
55 read_line_internal(reader:Pin::new(pointer:reader), cx, buf, bytes, read)
56 }
57}
58