4 self, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE,
9 /// Wraps a writer and buffers its output.
11 /// It can be excessively inefficient to work directly with something that
12 /// implements [`Write`]. For example, every call to
13 /// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A
14 /// `BufWriter<W>` keeps an in-memory buffer of data and writes it to an underlying
15 /// writer in large, infrequent batches.
17 /// `BufWriter<W>` can improve the speed of programs that make *small* and
18 /// *repeated* write calls to the same file or network socket. It does not
19 /// help when writing very large amounts at once, or writing just one or a few
20 /// times. It also provides no advantage when writing to a destination that is
21 /// in memory, like a <code>[Vec]\<u8></code>.
23 /// It is critical to call [`flush`] before `BufWriter<W>` is dropped. Though
24 /// dropping will attempt to flush the contents of the buffer, any errors
25 /// that happen in the process of dropping will be ignored. Calling [`flush`]
26 /// ensures that the buffer is empty and thus dropping will not even attempt
31 /// Let's write the numbers one through ten to a [`TcpStream`]:
34 /// use std::io::prelude::*;
35 /// use std::net::TcpStream;
37 /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
40 /// stream.write(&[i+1]).unwrap();
44 /// Because we're not buffering, we write each one in turn, incurring the
45 /// overhead of a system call per byte written. We can fix this with a
49 /// use std::io::prelude::*;
50 /// use std::io::BufWriter;
51 /// use std::net::TcpStream;
53 /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
56 /// stream.write(&[i+1]).unwrap();
58 /// stream.flush().unwrap();
61 /// By wrapping the stream with a `BufWriter<W>`, these ten writes are all grouped
62 /// together by the buffer and will all be written out in one system call when
63 /// the `stream` is flushed.
65 // HACK(#78696): can't use `crate` for associated items
66 /// [`TcpStream::write`]: super::super::super::net::TcpStream::write
67 /// [`TcpStream`]: crate::net::TcpStream
68 /// [`flush`]: BufWriter::flush
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub struct BufWriter<W: Write> {
72 // The buffer. Avoid using this like a normal `Vec` in common code paths.
73 // That is, don't use `buf.push`, `buf.extend_from_slice`, or any other
74 // methods that require bounds checking or the like. This makes an enormous
75 // difference to performance (we may want to stop using a `Vec` entirely).
77 // #30888: If the inner writer panics in a call to write, we don't want to
78 // write the buffered data a second time in BufWriter's destructor. This
79 // flag tells the Drop impl if it should skip the flush.
83 impl<W: Write> BufWriter<W> {
84 /// Creates a new `BufWriter<W>` with a default buffer capacity. The default is currently 8 KB,
85 /// but may change in the future.
90 /// use std::io::BufWriter;
91 /// use std::net::TcpStream;
93 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub fn new(inner: W) -> BufWriter<W> {
97 BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
100 /// Creates a new `BufWriter<W>` with the specified buffer capacity.
104 /// Creating a buffer with a buffer of a hundred bytes.
107 /// use std::io::BufWriter;
108 /// use std::net::TcpStream;
110 /// let stream = TcpStream::connect("127.0.0.1:34254").unwrap();
111 /// let mut buffer = BufWriter::with_capacity(100, stream);
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
115 BufWriter { inner, buf: Vec::with_capacity(capacity), panicked: false }
118 /// Send data in our local buffer into the inner writer, looping as
119 /// necessary until either it's all been sent or an error occurs.
121 /// Because all the data in the buffer has been reported to our owner as
122 /// "successfully written" (by returning nonzero success values from
123 /// `write`), any 0-length writes from `inner` must be reported as i/o
124 /// errors from this method.
125 pub(in crate::io) fn flush_buf(&mut self) -> io::Result<()> {
126 /// Helper struct to ensure the buffer is updated after all the writes
127 /// are complete. It tracks the number of written bytes and drains them
128 /// all from the front of the buffer when dropped.
129 struct BufGuard<'a> {
130 buffer: &'a mut Vec<u8>,
134 impl<'a> BufGuard<'a> {
135 fn new(buffer: &'a mut Vec<u8>) -> Self {
136 Self { buffer, written: 0 }
139 /// The unwritten part of the buffer
140 fn remaining(&self) -> &[u8] {
141 &self.buffer[self.written..]
144 /// Flag some bytes as removed from the front of the buffer
145 fn consume(&mut self, amt: usize) {
149 /// true if all of the bytes have been written
150 fn done(&self) -> bool {
151 self.written >= self.buffer.len()
155 impl Drop for BufGuard<'_> {
157 if self.written > 0 {
158 self.buffer.drain(..self.written);
163 let mut guard = BufGuard::new(&mut self.buf);
164 while !guard.done() {
165 self.panicked = true;
166 let r = self.inner.write(guard.remaining());
167 self.panicked = false;
171 return Err(io::const_io_error!(
172 ErrorKind::WriteZero,
173 "failed to write the buffered data",
176 Ok(n) => guard.consume(n),
177 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
178 Err(e) => return Err(e),
184 /// Buffer some data without flushing it, regardless of the size of the
185 /// data. Writes as much as possible without exceeding capacity. Returns
186 /// the number of bytes written.
187 pub(super) fn write_to_buf(&mut self, buf: &[u8]) -> usize {
188 let available = self.spare_capacity();
189 let amt_to_buffer = available.min(buf.len());
191 // SAFETY: `amt_to_buffer` is <= buffer's spare capacity by construction.
193 self.write_to_buffer_unchecked(&buf[..amt_to_buffer]);
199 /// Gets a reference to the underlying writer.
204 /// use std::io::BufWriter;
205 /// use std::net::TcpStream;
207 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
209 /// // we can use reference just like buffer
210 /// let reference = buffer.get_ref();
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn get_ref(&self) -> &W {
217 /// Gets a mutable reference to the underlying writer.
219 /// It is inadvisable to directly write to the underlying writer.
224 /// use std::io::BufWriter;
225 /// use std::net::TcpStream;
227 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
229 /// // we can use reference just like buffer
230 /// let reference = buffer.get_mut();
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn get_mut(&mut self) -> &mut W {
237 /// Returns a reference to the internally buffered data.
242 /// use std::io::BufWriter;
243 /// use std::net::TcpStream;
245 /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
247 /// // See how many bytes are currently buffered
248 /// let bytes_buffered = buf_writer.buffer().len();
250 #[stable(feature = "bufreader_buffer", since = "1.37.0")]
251 pub fn buffer(&self) -> &[u8] {
255 /// Returns a mutable reference to the internal buffer.
257 /// This can be used to write data directly into the buffer without triggering writers
258 /// to the underlying writer.
260 /// That the buffer is a `Vec` is an implementation detail.
261 /// Callers should not modify the capacity as there currently is no public API to do so
262 /// and thus any capacity changes would be unexpected by the user.
263 pub(in crate::io) fn buffer_mut(&mut self) -> &mut Vec<u8> {
267 /// Returns the number of bytes the internal buffer can hold without flushing.
272 /// use std::io::BufWriter;
273 /// use std::net::TcpStream;
275 /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
277 /// // Check the capacity of the inner buffer
278 /// let capacity = buf_writer.capacity();
279 /// // Calculate how many bytes can be written without flushing
280 /// let without_flush = capacity - buf_writer.buffer().len();
282 #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
283 pub fn capacity(&self) -> usize {
287 /// Unwraps this `BufWriter<W>`, returning the underlying writer.
289 /// The buffer is written out before returning the writer.
293 /// An [`Err`] will be returned if an error occurs while flushing the buffer.
298 /// use std::io::BufWriter;
299 /// use std::net::TcpStream;
301 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
303 /// // unwrap the TcpStream and flush the buffer
304 /// let stream = buffer.into_inner().unwrap();
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
308 match self.flush_buf() {
309 Err(e) => Err(IntoInnerError::new(self, e)),
310 Ok(()) => Ok(self.into_parts().0),
314 /// Disassembles this `BufWriter<W>`, returning the underlying writer, and any buffered but
317 /// If the underlying writer panicked, it is not known what portion of the data was written.
318 /// In this case, we return `WriterPanicked` for the buffered data (from which the buffer
319 /// contents can still be recovered).
321 /// `into_parts` makes no attempt to flush data and cannot fail.
326 /// use std::io::{BufWriter, Write};
328 /// let mut buffer = [0u8; 10];
329 /// let mut stream = BufWriter::new(buffer.as_mut());
330 /// write!(stream, "too much data").unwrap();
331 /// stream.flush().expect_err("it doesn't fit");
332 /// let (recovered_writer, buffered_data) = stream.into_parts();
333 /// assert_eq!(recovered_writer.len(), 0);
334 /// assert_eq!(&buffered_data.unwrap(), b"ata");
336 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
337 pub fn into_parts(mut self) -> (W, Result<Vec<u8>, WriterPanicked>) {
338 let buf = mem::take(&mut self.buf);
339 let buf = if !self.panicked { Ok(buf) } else { Err(WriterPanicked { buf }) };
341 // SAFETY: forget(self) prevents double dropping inner
342 let inner = unsafe { ptr::read(&mut self.inner) };
348 // Ensure this function does not get inlined into `write`, so that it
349 // remains inlineable and its common path remains as short as possible.
350 // If this function ends up being called frequently relative to `write`,
351 // it's likely a sign that the client is using an improperly sized buffer
352 // or their write patterns are somewhat pathological.
355 fn write_cold(&mut self, buf: &[u8]) -> io::Result<usize> {
356 if buf.len() > self.spare_capacity() {
360 // Why not len > capacity? To avoid a needless trip through the buffer when the input
361 // exactly fills it. We'd just need to flush it to the underlying writer anyway.
362 if buf.len() >= self.buf.capacity() {
363 self.panicked = true;
364 let r = self.get_mut().write(buf);
365 self.panicked = false;
368 // Write to the buffer. In this case, we write to the buffer even if it fills it
369 // exactly. Doing otherwise would mean flushing the buffer, then writing this
370 // input to the inner writer, which in many cases would be a worse strategy.
372 // SAFETY: There was either enough spare capacity already, or there wasn't and we
373 // flushed the buffer to ensure that there is. In the latter case, we know that there
374 // is because flushing ensured that our entire buffer is spare capacity, and we entered
375 // this block because the input buffer length is less than that capacity. In either
376 // case, it's safe to write the input buffer to our buffer.
378 self.write_to_buffer_unchecked(buf);
385 // Ensure this function does not get inlined into `write_all`, so that it
386 // remains inlineable and its common path remains as short as possible.
387 // If this function ends up being called frequently relative to `write_all`,
388 // it's likely a sign that the client is using an improperly sized buffer
389 // or their write patterns are somewhat pathological.
392 fn write_all_cold(&mut self, buf: &[u8]) -> io::Result<()> {
393 // Normally, `write_all` just calls `write` in a loop. We can do better
394 // by calling `self.get_mut().write_all()` directly, which avoids
395 // round trips through the buffer in the event of a series of partial
396 // writes in some circumstances.
398 if buf.len() > self.spare_capacity() {
402 // Why not len > capacity? To avoid a needless trip through the buffer when the input
403 // exactly fills it. We'd just need to flush it to the underlying writer anyway.
404 if buf.len() >= self.buf.capacity() {
405 self.panicked = true;
406 let r = self.get_mut().write_all(buf);
407 self.panicked = false;
410 // Write to the buffer. In this case, we write to the buffer even if it fills it
411 // exactly. Doing otherwise would mean flushing the buffer, then writing this
412 // input to the inner writer, which in many cases would be a worse strategy.
414 // SAFETY: There was either enough spare capacity already, or there wasn't and we
415 // flushed the buffer to ensure that there is. In the latter case, we know that there
416 // is because flushing ensured that our entire buffer is spare capacity, and we entered
417 // this block because the input buffer length is less than that capacity. In either
418 // case, it's safe to write the input buffer to our buffer.
420 self.write_to_buffer_unchecked(buf);
427 // SAFETY: Requires `buf.len() <= self.buf.capacity() - self.buf.len()`,
428 // i.e., that input buffer length is less than or equal to spare capacity.
430 unsafe fn write_to_buffer_unchecked(&mut self, buf: &[u8]) {
431 debug_assert!(buf.len() <= self.spare_capacity());
432 let old_len = self.buf.len();
433 let buf_len = buf.len();
434 let src = buf.as_ptr();
435 let dst = self.buf.as_mut_ptr().add(old_len);
436 ptr::copy_nonoverlapping(src, dst, buf_len);
437 self.buf.set_len(old_len + buf_len);
441 fn spare_capacity(&self) -> usize {
442 self.buf.capacity() - self.buf.len()
446 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
447 /// Error returned for the buffered data from `BufWriter::into_parts`, when the underlying
448 /// writer has previously panicked. Contains the (possibly partly written) buffered data.
453 /// use std::io::{self, BufWriter, Write};
454 /// use std::panic::{catch_unwind, AssertUnwindSafe};
456 /// struct PanickingWriter;
457 /// impl Write for PanickingWriter {
458 /// fn write(&mut self, buf: &[u8]) -> io::Result<usize> { panic!() }
459 /// fn flush(&mut self) -> io::Result<()> { panic!() }
462 /// let mut stream = BufWriter::new(PanickingWriter);
463 /// write!(stream, "some data").unwrap();
464 /// let result = catch_unwind(AssertUnwindSafe(|| {
465 /// stream.flush().unwrap()
467 /// assert!(result.is_err());
468 /// let (recovered_writer, buffered_data) = stream.into_parts();
469 /// assert!(matches!(recovered_writer, PanickingWriter));
470 /// assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data");
472 pub struct WriterPanicked {
476 impl WriterPanicked {
477 /// Returns the perhaps-unwritten data. Some of this data may have been written by the
478 /// panicking call(s) to the underlying writer, so simply writing it again is not a good idea.
479 #[must_use = "`self` will be dropped if the result is not used"]
480 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
481 pub fn into_inner(self) -> Vec<u8> {
485 const DESCRIPTION: &'static str =
486 "BufWriter inner writer panicked, what data remains unwritten is not known";
489 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
490 impl error::Error for WriterPanicked {
491 #[allow(deprecated, deprecated_in_future)]
492 fn description(&self) -> &str {
497 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
498 impl fmt::Display for WriterPanicked {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 write!(f, "{}", Self::DESCRIPTION)
504 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
505 impl fmt::Debug for WriterPanicked {
506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507 f.debug_struct("WriterPanicked")
508 .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<W: Write> Write for BufWriter<W> {
516 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
517 // Use < instead of <= to avoid a needless trip through the buffer in some cases.
518 // See `write_cold` for details.
519 if buf.len() < self.spare_capacity() {
520 // SAFETY: safe by above conditional.
522 self.write_to_buffer_unchecked(buf);
532 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
533 // Use < instead of <= to avoid a needless trip through the buffer in some cases.
534 // See `write_all_cold` for details.
535 if buf.len() < self.spare_capacity() {
536 // SAFETY: safe by above conditional.
538 self.write_to_buffer_unchecked(buf);
543 self.write_all_cold(buf)
547 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
548 // FIXME: Consider applying `#[inline]` / `#[inline(never)]` optimizations already applied
549 // to `write` and `write_all`. The performance benefits can be significant. See #79930.
550 if self.get_ref().is_write_vectored() {
551 // We have to handle the possibility that the total length of the buffers overflows
552 // `usize` (even though this can only happen if multiple `IoSlice`s reference the
553 // same underlying buffer, as otherwise the buffers wouldn't fit in memory). If the
554 // computation overflows, then surely the input cannot fit in our buffer, so we forward
555 // to the inner writer's `write_vectored` method to let it handle it appropriately.
556 let saturated_total_len =
557 bufs.iter().fold(0usize, |acc, b| acc.saturating_add(b.len()));
559 if saturated_total_len > self.spare_capacity() {
560 // Flush if the total length of the input exceeds our buffer's spare capacity.
561 // If we would have overflowed, this condition also holds, and we need to flush.
565 if saturated_total_len >= self.buf.capacity() {
566 // Forward to our inner writer if the total length of the input is greater than or
567 // equal to our buffer capacity. If we would have overflowed, this condition also
568 // holds, and we punt to the inner writer.
569 self.panicked = true;
570 let r = self.get_mut().write_vectored(bufs);
571 self.panicked = false;
574 // `saturated_total_len < self.buf.capacity()` implies that we did not saturate.
576 // SAFETY: We checked whether or not the spare capacity was large enough above. If
577 // it was, then we're safe already. If it wasn't, we flushed, making sufficient
578 // room for any input <= the buffer size, which includes this input.
580 bufs.iter().for_each(|b| self.write_to_buffer_unchecked(b));
583 Ok(saturated_total_len)
586 let mut iter = bufs.iter();
587 let mut total_written = if let Some(buf) = iter.by_ref().find(|&buf| !buf.is_empty()) {
588 // This is the first non-empty slice to write, so if it does
589 // not fit in the buffer, we still get to flush and proceed.
590 if buf.len() > self.spare_capacity() {
593 if buf.len() >= self.buf.capacity() {
594 // The slice is at least as large as the buffering capacity,
595 // so it's better to write it directly, bypassing the buffer.
596 self.panicked = true;
597 let r = self.get_mut().write(buf);
598 self.panicked = false;
601 // SAFETY: We checked whether or not the spare capacity was large enough above.
602 // If it was, then we're safe already. If it wasn't, we flushed, making
603 // sufficient room for any input <= the buffer size, which includes this input.
605 self.write_to_buffer_unchecked(buf);
613 debug_assert!(total_written != 0);
615 if buf.len() <= self.spare_capacity() {
616 // SAFETY: safe by above conditional.
618 self.write_to_buffer_unchecked(buf);
621 // This cannot overflow `usize`. If we are here, we've written all of the bytes
622 // so far to our buffer, and we've ensured that we never exceed the buffer's
623 // capacity. Therefore, `total_written` <= `self.buf.capacity()` <= `usize::MAX`.
624 total_written += buf.len();
633 fn is_write_vectored(&self) -> bool {
637 fn flush(&mut self) -> io::Result<()> {
638 self.flush_buf().and_then(|()| self.get_mut().flush())
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<W: Write> fmt::Debug for BufWriter<W>
647 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
648 fmt.debug_struct("BufWriter")
649 .field("writer", &self.inner)
650 .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl<W: Write + Seek> Seek for BufWriter<W> {
657 /// Seek to the offset, in bytes, in the underlying writer.
659 /// Seeking always writes out the internal buffer before seeking.
660 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
662 self.get_mut().seek(pos)
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<W: Write> Drop for BufWriter<W> {
670 // dtors should not panic, so we ignore a failed flush
671 let _r = self.flush_buf();