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