Skip to main content

tokio/io/util/
buf_stream.rs

1use crate::io::util::{BufReader, BufWriter};
2use crate::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};
3
4use pin_project_lite::pin_project;
5use std::io::{self, IoSlice, SeekFrom};
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9pin_project! {
10    /// Wraps a type that is [`AsyncWrite`] and [`AsyncRead`], and buffers its input and output.
11    ///
12    /// It can be excessively inefficient to work directly with something that implements [`AsyncWrite`]
13    /// and [`AsyncRead`]. For example, every `write`, however small, has to traverse the syscall
14    /// interface, and similarly, every read has to do the same. The [`BufWriter`] and [`BufReader`]
15    /// types aid with these problems respectively, but do so in only one direction. `BufStream` wraps
16    /// one in the other so that both directions are buffered. See their documentation for details.
17    #[derive(Debug)]
18    #[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
19    pub struct BufStream<RW> {
20        #[pin]
21        inner: BufReader<BufWriter<RW>>,
22    }
23}
24
25impl<RW: AsyncRead + AsyncWrite> BufStream<RW> {
26    /// Wraps a type in both [`BufWriter`] and [`BufReader`].
27    ///
28    /// See the documentation for those types and [`BufStream`] for details.
29    pub fn new(stream: RW) -> BufStream<RW> {
30        BufStream {
31            inner: BufReader::new(BufWriter::new(stream)),
32        }
33    }
34
35    /// Creates a `BufStream` with the specified [`BufReader`] capacity and [`BufWriter`]
36    /// capacity.
37    ///
38    /// See the documentation for those types and [`BufStream`] for details.
39    ///
40    /// # Panics
41    ///
42    /// Panics if `reader_capacity` is zero.
43    #[track_caller]
44    pub fn with_capacity(
45        reader_capacity: usize,
46        writer_capacity: usize,
47        stream: RW,
48    ) -> BufStream<RW> {
49        BufStream {
50            inner: BufReader::with_capacity(
51                reader_capacity,
52                BufWriter::with_capacity(writer_capacity, stream),
53            ),
54        }
55    }
56
57    /// Gets a reference to the underlying I/O object.
58    ///
59    /// It is inadvisable to directly read from the underlying I/O object.
60    pub fn get_ref(&self) -> &RW {
61        self.inner.get_ref().get_ref()
62    }
63
64    /// Gets a mutable reference to the underlying I/O object.
65    ///
66    /// It is inadvisable to directly read from the underlying I/O object.
67    pub fn get_mut(&mut self) -> &mut RW {
68        self.inner.get_mut().get_mut()
69    }
70
71    /// Gets a pinned mutable reference to the underlying I/O object.
72    ///
73    /// It is inadvisable to directly read from the underlying I/O object.
74    pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut RW> {
75        self.project().inner.get_pin_mut().get_pin_mut()
76    }
77
78    /// Consumes this `BufStream`, returning the underlying I/O object.
79    ///
80    /// Note that any leftover data in the internal buffer is lost.
81    pub fn into_inner(self) -> RW {
82        self.inner.into_inner().into_inner()
83    }
84}
85
86impl<RW> From<BufReader<BufWriter<RW>>> for BufStream<RW> {
87    fn from(b: BufReader<BufWriter<RW>>) -> Self {
88        BufStream { inner: b }
89    }
90}
91
92impl<RW> From<BufWriter<BufReader<RW>>> for BufStream<RW> {
93    fn from(b: BufWriter<BufReader<RW>>) -> Self {
94        // we need to "invert" the reader and writer
95        let BufWriter {
96            inner:
97                BufReader {
98                    inner,
99                    buf: rbuf,
100                    pos,
101                    cap,
102                    seek_state: rseek_state,
103                },
104            buf: wbuf,
105            written,
106            seek_state: wseek_state,
107        } = b;
108
109        BufStream {
110            inner: BufReader {
111                inner: BufWriter {
112                    inner,
113                    buf: wbuf,
114                    written,
115                    seek_state: wseek_state,
116                },
117                buf: rbuf,
118                pos,
119                cap,
120                seek_state: rseek_state,
121            },
122        }
123    }
124}
125
126impl<RW: AsyncRead + AsyncWrite> AsyncWrite for BufStream<RW> {
127    fn poll_write(
128        self: Pin<&mut Self>,
129        cx: &mut Context<'_>,
130        buf: &[u8],
131    ) -> Poll<io::Result<usize>> {
132        self.project().inner.poll_write(cx, buf)
133    }
134
135    fn poll_write_vectored(
136        self: Pin<&mut Self>,
137        cx: &mut Context<'_>,
138        bufs: &[IoSlice<'_>],
139    ) -> Poll<io::Result<usize>> {
140        self.project().inner.poll_write_vectored(cx, bufs)
141    }
142
143    fn is_write_vectored(&self) -> bool {
144        self.inner.is_write_vectored()
145    }
146
147    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
148        self.project().inner.poll_flush(cx)
149    }
150
151    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
152        self.project().inner.poll_shutdown(cx)
153    }
154}
155
156impl<RW: AsyncRead + AsyncWrite> AsyncRead for BufStream<RW> {
157    fn poll_read(
158        self: Pin<&mut Self>,
159        cx: &mut Context<'_>,
160        buf: &mut ReadBuf<'_>,
161    ) -> Poll<io::Result<()>> {
162        self.project().inner.poll_read(cx, buf)
163    }
164}
165
166/// Seek to an offset, in bytes, in the underlying stream.
167///
168/// The position used for seeking with `SeekFrom::Current(_)` is the
169/// position the underlying stream would be at if the `BufStream` had no
170/// internal buffer.
171///
172/// Seeking always discards the internal buffer, even if the seek position
173/// would otherwise fall within it. This guarantees that calling
174/// `.into_inner()` immediately after a seek yields the underlying reader
175/// at the same position.
176///
177/// See [`AsyncSeek`] for more details.
178///
179/// Note: In the edge case where you're seeking with `SeekFrom::Current(n)`
180/// where `n` minus the internal buffer length overflows an `i64`, two
181/// seeks will be performed instead of one. If the second seek returns
182/// `Err`, the underlying reader will be left at the same position it would
183/// have if you called `seek` with `SeekFrom::Current(0)`.
184impl<RW: AsyncRead + AsyncWrite + AsyncSeek> AsyncSeek for BufStream<RW> {
185    fn start_seek(self: Pin<&mut Self>, position: SeekFrom) -> io::Result<()> {
186        self.project().inner.start_seek(position)
187    }
188
189    fn poll_complete(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
190        self.project().inner.poll_complete(cx)
191    }
192}
193
194impl<RW: AsyncRead + AsyncWrite> AsyncBufRead for BufStream<RW> {
195    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
196        self.project().inner.poll_fill_buf(cx)
197    }
198
199    fn consume(self: Pin<&mut Self>, amt: usize) {
200        self.project().inner.consume(amt);
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn assert_unpin() {
210        crate::is_unpin::<BufStream<()>>();
211    }
212}