compio_io/write/
buf.rs

1use compio_buf::{BufResult, IntoInner, IoBuf, IoVectoredBuf, buf_try};
2
3use crate::{
4    AsyncWrite, IoResult,
5    buffer::Buffer,
6    util::{DEFAULT_BUF_SIZE, slice_to_buf},
7};
8
9/// Wraps a writer and buffers its output.
10///
11/// It can be excessively inefficient to work directly with something that
12/// implements [`AsyncWrite`].  A `BufWriter<W>` keeps an in-memory buffer of
13/// data and writes it to an underlying writer in large, infrequent batches.
14//
15/// `BufWriter<W>` can improve the speed of programs that make *small* and
16/// *repeated* write calls to the same file or network socket. It does not
17/// help when writing very large amounts at once, or writing just one or a few
18/// times. It also provides no advantage when writing to a destination that is
19/// in memory, like a `Vec<u8>`.
20///
21/// Dropping `BufWriter<W>` also discards any bytes left in the buffer, so it is
22/// critical to call [`flush`] before `BufWriter<W>` is dropped. Calling
23/// [`flush`] ensures that the buffer is empty and thus no data is lost.
24///
25/// [`flush`]: AsyncWrite::flush
26
27#[derive(Debug)]
28pub struct BufWriter<W> {
29    writer: W,
30    buf: Buffer,
31}
32
33impl<W> BufWriter<W> {
34    /// Creates a new `BufWriter` with a default buffer capacity. The default is
35    /// currently 8 KiB, but may change in the future.
36    pub fn new(writer: W) -> Self {
37        Self::with_capacity(DEFAULT_BUF_SIZE, writer)
38    }
39
40    /// Creates a new `BufWriter` with the specified buffer capacity.
41    pub fn with_capacity(cap: usize, writer: W) -> Self {
42        Self {
43            writer,
44            buf: Buffer::with_capacity(cap),
45        }
46    }
47}
48
49impl<W: AsyncWrite> BufWriter<W> {
50    async fn flush_if_needed(&mut self) -> IoResult<()> {
51        if self.buf.need_flush() {
52            self.flush().await?;
53        }
54        Ok(())
55    }
56}
57
58impl<W: AsyncWrite> AsyncWrite for BufWriter<W> {
59    async fn write<T: IoBuf>(&mut self, mut buf: T) -> BufResult<usize, T> {
60        // The previous flush may error because disk full. We need to make the buffer
61        // all-done before writing new data to it.
62        (_, buf) = buf_try!(self.flush_if_needed().await, buf);
63
64        let written = self
65            .buf
66            .with_sync(|w| {
67                let len = w.buf_len();
68                let mut w = w.slice(len..);
69                let written = slice_to_buf(buf.as_slice(), &mut w);
70                BufResult(Ok(written), w.into_inner())
71            })
72            .expect("Closure always return Ok");
73
74        (_, buf) = buf_try!(self.flush_if_needed().await, buf);
75
76        BufResult(Ok(written), buf)
77    }
78
79    async fn write_vectored<T: IoVectoredBuf>(&mut self, mut buf: T) -> BufResult<usize, T> {
80        (_, buf) = buf_try!(self.flush_if_needed().await, buf);
81
82        let written = self
83            .buf
84            .with_sync(|mut w| {
85                let mut written = 0;
86                for buf in buf.iter_slice() {
87                    let len = w.buf_len();
88                    let mut slice = w.slice(len..);
89                    written += slice_to_buf(buf, &mut slice);
90                    w = slice.into_inner();
91
92                    if w.buf_len() == w.buf_capacity() {
93                        break;
94                    }
95                }
96                BufResult(Ok(written), w)
97            })
98            .expect("Closure always return Ok");
99
100        (_, buf) = buf_try!(self.flush_if_needed().await, buf);
101
102        BufResult(Ok(written), buf)
103    }
104
105    async fn flush(&mut self) -> IoResult<()> {
106        let Self { writer, buf } = self;
107
108        buf.flush_to(writer).await?;
109
110        Ok(())
111    }
112
113    async fn shutdown(&mut self) -> IoResult<()> {
114        self.flush().await?;
115        self.writer.shutdown().await
116    }
117}
118
119impl<W> IntoInner for BufWriter<W> {
120    type Inner = W;
121
122    fn into_inner(self) -> Self::Inner {
123        self.writer
124    }
125}