tokio_stream/wrappers/
lines.rs

1use crate::Stream;
2use pin_project_lite::pin_project;
3use std::io;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6use tokio::io::{AsyncBufRead, Lines};
7
8pin_project! {
9    /// A wrapper around [`tokio::io::Lines`] that implements [`Stream`].
10    ///
11    /// [`tokio::io::Lines`]: struct@tokio::io::Lines
12    /// [`Stream`]: trait@crate::Stream
13    #[derive(Debug)]
14    #[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
15    pub struct LinesStream<R> {
16        #[pin]
17        inner: Lines<R>,
18    }
19}
20
21impl<R> LinesStream<R> {
22    /// Create a new `LinesStream`.
23    pub fn new(lines: Lines<R>) -> Self {
24        Self { inner: lines }
25    }
26
27    /// Get back the inner `Lines`.
28    pub fn into_inner(self) -> Lines<R> {
29        self.inner
30    }
31
32    /// Obtain a pinned reference to the inner `Lines<R>`.
33    pub fn as_pin_mut(self: Pin<&mut Self>) -> Pin<&mut Lines<R>> {
34        self.project().inner
35    }
36}
37
38impl<R: AsyncBufRead> Stream for LinesStream<R> {
39    type Item = io::Result<String>;
40
41    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
42        self.project()
43            .inner
44            .poll_next_line(cx)
45            .map(Result::transpose)
46    }
47}
48
49impl<R> AsRef<Lines<R>> for LinesStream<R> {
50    fn as_ref(&self) -> &Lines<R> {
51        &self.inner
52    }
53}
54
55impl<R> AsMut<Lines<R>> for LinesStream<R> {
56    fn as_mut(&mut self) -> &mut Lines<R> {
57        &mut self.inner
58    }
59}