async_std/io/
buf_writer.rs

1use std::fmt;
2use std::pin::Pin;
3
4use pin_project_lite::pin_project;
5
6use crate::io::write::WriteExt;
7use crate::io::{self, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE};
8use crate::task::{Context, Poll, ready};
9
10pin_project! {
11    /// Wraps a writer and buffers its output.
12    ///
13    /// It can be excessively inefficient to work directly with something that
14    /// implements [`Write`]. For example, every call to
15    /// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A
16    /// `BufWriter` keeps an in-memory buffer of data and writes it to an underlying
17    /// writer in large, infrequent batches.
18    ///
19    /// `BufWriter` can improve the speed of programs that make *small* and
20    /// *repeated* write calls to the same file or network socket. It does not
21    /// help when writing very large amounts at once, or writing just one or a few
22    /// times. It also provides no advantage when writing to a destination that is
23    /// in memory, like a `Vec<u8>`.
24    ///
25    /// Unlike the `BufWriter` type in `std`, this type does not write out the
26    /// contents of its buffer when it is dropped. Therefore, it is absolutely
27    /// critical that users explicitly flush the buffer before dropping a
28    /// `BufWriter`.
29    ///
30    /// This type is an async version of [`std::io::BufWriter`].
31    ///
32    /// [`std::io::BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
33    ///
34    /// # Examples
35    ///
36    /// Let's write the numbers one through ten to a [`TcpStream`]:
37    ///
38    /// ```no_run
39    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
40    /// use async_std::net::TcpStream;
41    /// use async_std::prelude::*;
42    ///
43    /// let mut stream = TcpStream::connect("127.0.0.1:34254").await?;
44    ///
45    /// for i in 0..10 {
46    ///     let arr = [i+1];
47    ///     stream.write(&arr).await?;
48    /// }
49    /// #
50    /// # Ok(()) }) }
51    /// ```
52    ///
53    /// Because we're not buffering, we write each one in turn, incurring the
54    /// overhead of a system call per byte written. We can fix this with a
55    /// `BufWriter`:
56    ///
57    /// ```no_run
58    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
59    /// use async_std::io::BufWriter;
60    /// use async_std::net::TcpStream;
61    /// use async_std::prelude::*;
62    ///
63    /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").await?);
64    ///
65    /// for i in 0..10 {
66    ///     let arr = [i+1];
67    ///     stream.write(&arr).await?;
68    /// };
69    ///
70    /// stream.flush().await?;
71    /// #
72    /// # Ok(()) }) }
73    /// ```
74    ///
75    /// By wrapping the stream with a `BufWriter`, these ten writes are all grouped
76    /// together by the buffer, and will all be written out in one system call when
77    /// the `stream` is dropped.
78    ///
79    /// [`Write`]: trait.Write.html
80    /// [`TcpStream::write`]: ../net/struct.TcpStream.html#method.write
81    /// [`TcpStream`]: ../net/struct.TcpStream.html
82    /// [`flush`]: trait.Write.html#tymethod.flush
83    pub struct BufWriter<W> {
84        #[pin]
85        inner: W,
86        buf: Vec<u8>,
87        written: usize,
88    }
89}
90
91/// An error returned by `into_inner` which combines an error that
92/// happened while writing out the buffer, and the buffered writer object
93/// which may be used to recover from the condition.
94///
95/// # Examples
96///
97/// ```no_run
98/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
99/// use async_std::io::BufWriter;
100/// use async_std::net::TcpStream;
101///
102/// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34251").await?);
103///
104/// // unwrap the TcpStream and flush the buffer
105/// let stream = match buf_writer.into_inner().await {
106///     Ok(s) => s,
107///     Err(e) => {
108///         // Here, e is an IntoInnerError
109///         panic!("An error occurred");
110///     }
111/// };
112/// #
113/// # Ok(()) }) }
114///```
115#[derive(Debug)]
116pub struct IntoInnerError<W>(W, crate::io::Error);
117
118impl<W: Write> BufWriter<W> {
119    /// Creates a new `BufWriter` with a default buffer capacity. The default is currently 8 KB,
120    /// but may change in the future.
121    ///
122    /// # Examples
123    ///
124    /// ```no_run
125    /// # #![allow(unused_mut)]
126    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
127    /// use async_std::io::BufWriter;
128    /// use async_std::net::TcpStream;
129    ///
130    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").await?);
131    /// #
132    /// # Ok(()) }) }
133    /// ```
134    pub fn new(inner: W) -> BufWriter<W> {
135        BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
136    }
137
138    /// Creates a new `BufWriter` with the specified buffer capacity.
139    ///
140    /// # Examples
141    ///
142    /// Creating a buffer with a buffer of a hundred bytes.
143    ///
144    /// ```no_run
145    /// # #![allow(unused_mut)]
146    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
147    /// use async_std::io::BufWriter;
148    /// use async_std::net::TcpStream;
149    ///
150    /// let stream = TcpStream::connect("127.0.0.1:34254").await?;
151    /// let mut buffer = BufWriter::with_capacity(100, stream);
152    /// #
153    /// # Ok(()) }) }
154    /// ```
155    pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
156        BufWriter {
157            inner,
158            buf: Vec::with_capacity(capacity),
159            written: 0,
160        }
161    }
162
163    /// Gets a reference to the underlying writer.
164    ///
165    /// # Examples
166    ///
167    /// ```no_run
168    /// # #![allow(unused_mut)]
169    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
170    /// use async_std::io::BufWriter;
171    /// use async_std::net::TcpStream;
172    ///
173    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").await?);
174    ///
175    /// // We can use reference just like buffer
176    /// let reference = buffer.get_ref();
177    /// #
178    /// # Ok(()) }) }
179    /// ```
180    pub fn get_ref(&self) -> &W {
181        &self.inner
182    }
183
184    /// Gets a mutable reference to the underlying writer.
185    ///
186    /// It is inadvisable to directly write to the underlying writer.
187    ///
188    /// # Examples
189    ///
190    /// ```no_run
191    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
192    /// use async_std::io::BufWriter;
193    /// use async_std::net::TcpStream;
194    ///
195    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").await?);
196    ///
197    /// // We can use reference just like buffer
198    /// let reference = buffer.get_mut();
199    /// #
200    /// # Ok(()) }) }
201    /// ```
202    pub fn get_mut(&mut self) -> &mut W {
203        &mut self.inner
204    }
205
206    /// Gets a pinned mutable reference to the underlying writer.
207    ///
208    /// It is inadvisable to directly write to the underlying writer.
209    fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> {
210        self.project().inner
211    }
212
213    /// Consumes BufWriter, returning the underlying writer
214    ///
215    /// This method will not write leftover data, it will be lost.
216    /// For method that will attempt to write before returning the writer see [`poll_into_inner`]
217    ///
218    /// [`poll_into_inner`]: #method.poll_into_inner
219    /// # Examples
220    ///
221    /// ```no_run
222    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
223    /// use async_std::io::BufWriter;
224    /// use async_std::net::TcpStream;
225    ///
226    /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34251").await?);
227    ///
228    /// // unwrap the TcpStream and flush the buffer
229    /// let stream = buf_writer.into_inner().await.unwrap();
230    /// #
231    /// # Ok(()) }) }
232    /// ```
233    pub async fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>>
234    where
235        Self: Unpin,
236    {
237        match self.flush().await {
238            Err(e) => Err(IntoInnerError(self, e)),
239            Ok(()) => Ok(self.inner),
240        }
241    }
242
243    /// Returns a reference to the internally buffered data.
244    ///
245    /// # Examples
246    ///
247    /// ```no_run
248    /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
249    /// use async_std::io::BufWriter;
250    /// use async_std::net::TcpStream;
251    ///
252    /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34251").await?);
253    ///
254    /// // See how many bytes are currently buffered
255    /// let bytes_buffered = buf_writer.buffer().len();
256    /// #
257    /// # Ok(()) }) }
258    /// ```
259    pub fn buffer(&self) -> &[u8] {
260        &self.buf
261    }
262
263    /// Poll buffer flushing until completion
264    ///
265    /// This is used in types that wrap around BufWrite, one such example: [`LineWriter`]
266    ///
267    /// [`LineWriter`]: struct.LineWriter.html
268    fn poll_flush_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
269        let mut this = self.project();
270        let len = this.buf.len();
271        let mut ret = Ok(());
272        while *this.written < len {
273            match this
274                .inner
275                .as_mut()
276                .poll_write(cx, &this.buf[*this.written..])
277            {
278                Poll::Ready(Ok(0)) => {
279                    ret = Err(io::Error::new(
280                        io::ErrorKind::WriteZero,
281                        "Failed to write buffered data",
282                    ));
283                    break;
284                }
285                Poll::Ready(Ok(n)) => *this.written += n,
286                Poll::Ready(Err(ref e)) if e.kind() == io::ErrorKind::Interrupted => {}
287                Poll::Ready(Err(e)) => {
288                    ret = Err(e);
289                    break;
290                }
291                Poll::Pending => return Poll::Pending,
292            }
293        }
294        if *this.written > 0 {
295            this.buf.drain(..*this.written);
296        }
297        *this.written = 0;
298        Poll::Ready(ret)
299    }
300}
301
302impl<W: Write> Write for BufWriter<W> {
303    fn poll_write(
304        mut self: Pin<&mut Self>,
305        cx: &mut Context<'_>,
306        buf: &[u8],
307    ) -> Poll<io::Result<usize>> {
308        if self.buf.len() + buf.len() > self.buf.capacity() {
309            ready!(self.as_mut().poll_flush_buf(cx))?;
310        }
311        if buf.len() >= self.buf.capacity() {
312            self.get_pin_mut().poll_write(cx, buf)
313        } else {
314            Pin::new(&mut *self.project().buf).poll_write(cx, buf)
315        }
316    }
317
318    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
319        ready!(self.as_mut().poll_flush_buf(cx))?;
320        self.get_pin_mut().poll_flush(cx)
321    }
322
323    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
324        ready!(self.as_mut().poll_flush_buf(cx))?;
325        self.get_pin_mut().poll_close(cx)
326    }
327}
328
329impl<W: Write + fmt::Debug> fmt::Debug for BufWriter<W> {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        f.debug_struct("BufWriter")
332            .field("writer", &self.inner)
333            .field("buf", &self.buf)
334            .finish()
335    }
336}
337
338impl<W: Write + Seek> Seek for BufWriter<W> {
339    /// Seek to the offset, in bytes, in the underlying writer.
340    ///
341    /// Seeking always writes out the internal buffer before seeking.
342    fn poll_seek(
343        mut self: Pin<&mut Self>,
344        cx: &mut Context<'_>,
345        pos: SeekFrom,
346    ) -> Poll<io::Result<u64>> {
347        ready!(self.as_mut().poll_flush_buf(cx))?;
348        self.get_pin_mut().poll_seek(cx, pos)
349    }
350}