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    /// # Example
12    ///
13    /// ```
14    /// use tokio::io::AsyncBufReadExt;
15    /// use tokio_stream::wrappers::LinesStream;
16    /// use tokio_stream::StreamExt;
17    ///
18    /// # #[tokio::main(flavor = "current_thread")]
19    /// # async fn main() -> std::io::Result<()> {
20    /// let input = b"Hello\nWorld\n";
21    /// let mut stream = LinesStream::new(input.lines());
22    /// while let Some(line) = stream.next().await {
23    ///     println!("{}", line?);
24    /// }
25    /// # Ok(())
26    /// # }
27    /// ```
28    ///
29    /// [`tokio::io::Lines`]: struct@tokio::io::Lines
30    /// [`Stream`]: trait@crate::Stream
31    #[derive(Debug)]
32    #[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
33    pub struct LinesStream<R> {
34        #[pin]
35        inner: Lines<R>,
36    }
37}
38
39impl<R> LinesStream<R> {
40    /// Create a new `LinesStream`.
41    pub fn new(lines: Lines<R>) -> Self {
42        Self { inner: lines }
43    }
44
45    /// Get back the inner `Lines`.
46    pub fn into_inner(self) -> Lines<R> {
47        self.inner
48    }
49
50    /// Obtain a pinned reference to the inner `Lines<R>`.
51    pub fn as_pin_mut(self: Pin<&mut Self>) -> Pin<&mut Lines<R>> {
52        self.project().inner
53    }
54}
55
56impl<R: AsyncBufRead> Stream for LinesStream<R> {
57    type Item = io::Result<String>;
58
59    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
60        self.project()
61            .inner
62            .poll_next_line(cx)
63            .map(Result::transpose)
64    }
65}
66
67impl<R> AsRef<Lines<R>> for LinesStream<R> {
68    fn as_ref(&self) -> &Lines<R> {
69        &self.inner
70    }
71}
72
73impl<R> AsMut<Lines<R>> for LinesStream<R> {
74    fn as_mut(&mut self) -> &mut Lines<R> {
75        &mut self.inner
76    }
77}