std/io/buffered/
bufwriter.rs

1use crate::io::{
2    self, DEFAULT_BUF_SIZE, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write,
3};
4use crate::mem::{self, ManuallyDrop};
5use crate::{error, fmt, ptr};
6
7/// Wraps a writer and buffers its output.
8///
9/// It can be excessively inefficient to work directly with something that
10/// implements [`Write`]. For example, every call to
11/// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A
12/// `BufWriter<W>` keeps an in-memory buffer of data and writes it to an underlying
13/// 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 <code>[Vec]\<u8></code>.
20///
21/// It is critical to call [`flush`] before `BufWriter<W>` is dropped. Though
22/// dropping will attempt to flush the contents of the buffer, any errors
23/// that happen in the process of dropping will be ignored. Calling [`flush`]
24/// ensures that the buffer is empty and thus dropping will not even attempt
25/// file operations.
26///
27/// # Examples
28///
29/// Let's write the numbers one through ten to a [`TcpStream`]:
30///
31/// ```no_run
32/// use std::io::prelude::*;
33/// use std::net::TcpStream;
34///
35/// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
36///
37/// for i in 0..10 {
38///     stream.write(&[i+1]).unwrap();
39/// }
40/// ```
41///
42/// Because we're not buffering, we write each one in turn, incurring the
43/// overhead of a system call per byte written. We can fix this with a
44/// `BufWriter<W>`:
45///
46/// ```no_run
47/// use std::io::prelude::*;
48/// use std::io::BufWriter;
49/// use std::net::TcpStream;
50///
51/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
52///
53/// for i in 0..10 {
54///     stream.write(&[i+1]).unwrap();
55/// }
56/// stream.flush().unwrap();
57/// ```
58///
59/// By wrapping the stream with a `BufWriter<W>`, these ten writes are all grouped
60/// together by the buffer and will all be written out in one system call when
61/// the `stream` is flushed.
62///
63/// [`TcpStream::write`]: crate::net::TcpStream::write
64/// [`TcpStream`]: crate::net::TcpStream
65/// [`flush`]: BufWriter::flush
66#[stable(feature = "rust1", since = "1.0.0")]
67pub struct BufWriter<W: ?Sized + Write> {
68    // The buffer. Avoid using this like a normal `Vec` in common code paths.
69    // That is, don't use `buf.push`, `buf.extend_from_slice`, or any other
70    // methods that require bounds checking or the like. This makes an enormous
71    // difference to performance (we may want to stop using a `Vec` entirely).
72    buf: Vec<u8>,
73    // #30888: If the inner writer panics in a call to write, we don't want to
74    // write the buffered data a second time in BufWriter's destructor. This
75    // flag tells the Drop impl if it should skip the flush.
76    panicked: bool,
77    inner: W,
78}
79
80impl<W: Write> BufWriter<W> {
81    /// Creates a new `BufWriter<W>` with a default buffer capacity. The default is currently 8 KiB,
82    /// but may change in the future.
83    ///
84    /// # Examples
85    ///
86    /// ```no_run
87    /// use std::io::BufWriter;
88    /// use std::net::TcpStream;
89    ///
90    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
91    /// ```
92    #[stable(feature = "rust1", since = "1.0.0")]
93    pub fn new(inner: W) -> BufWriter<W> {
94        BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
95    }
96
97    pub(crate) fn try_new_buffer() -> io::Result<Vec<u8>> {
98        Vec::try_with_capacity(DEFAULT_BUF_SIZE).map_err(|_| {
99            io::const_error!(ErrorKind::OutOfMemory, "failed to allocate write buffer")
100        })
101    }
102
103    pub(crate) fn with_buffer(inner: W, buf: Vec<u8>) -> Self {
104        Self { inner, buf, panicked: false }
105    }
106
107    /// Creates a new `BufWriter<W>` with at least the specified buffer capacity.
108    ///
109    /// # Examples
110    ///
111    /// Creating a buffer with a buffer of at least a hundred bytes.
112    ///
113    /// ```no_run
114    /// use std::io::BufWriter;
115    /// use std::net::TcpStream;
116    ///
117    /// let stream = TcpStream::connect("127.0.0.1:34254").unwrap();
118    /// let mut buffer = BufWriter::with_capacity(100, stream);
119    /// ```
120    #[stable(feature = "rust1", since = "1.0.0")]
121    pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
122        BufWriter { inner, buf: Vec::with_capacity(capacity), panicked: false }
123    }
124
125    /// Unwraps this `BufWriter<W>`, returning the underlying writer.
126    ///
127    /// The buffer is written out before returning the writer.
128    ///
129    /// # Errors
130    ///
131    /// An [`Err`] will be returned if an error occurs while flushing the buffer.
132    ///
133    /// # Examples
134    ///
135    /// ```no_run
136    /// use std::io::BufWriter;
137    /// use std::net::TcpStream;
138    ///
139    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
140    ///
141    /// // unwrap the TcpStream and flush the buffer
142    /// let stream = buffer.into_inner().unwrap();
143    /// ```
144    #[stable(feature = "rust1", since = "1.0.0")]
145    pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
146        match self.flush_buf() {
147            Err(e) => Err(IntoInnerError::new(self, e)),
148            Ok(()) => Ok(self.into_parts().0),
149        }
150    }
151
152    /// Disassembles this `BufWriter<W>`, returning the underlying writer, and any buffered but
153    /// unwritten data.
154    ///
155    /// If the underlying writer panicked, it is not known what portion of the data was written.
156    /// In this case, we return `WriterPanicked` for the buffered data (from which the buffer
157    /// contents can still be recovered).
158    ///
159    /// `into_parts` makes no attempt to flush data and cannot fail.
160    ///
161    /// # Examples
162    ///
163    /// ```
164    /// use std::io::{BufWriter, Write};
165    ///
166    /// let mut buffer = [0u8; 10];
167    /// let mut stream = BufWriter::new(buffer.as_mut());
168    /// write!(stream, "too much data").unwrap();
169    /// stream.flush().expect_err("it doesn't fit");
170    /// let (recovered_writer, buffered_data) = stream.into_parts();
171    /// assert_eq!(recovered_writer.len(), 0);
172    /// assert_eq!(&buffered_data.unwrap(), b"ata");
173    /// ```
174    #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
175    pub fn into_parts(self) -> (W, Result<Vec<u8>, WriterPanicked>) {
176        let mut this = ManuallyDrop::new(self);
177        let buf = mem::take(&mut this.buf);
178        let buf = if !this.panicked { Ok(buf) } else { Err(WriterPanicked { buf }) };
179
180        // SAFETY: double-drops are prevented by putting `this` in a ManuallyDrop that is never dropped
181        let inner = unsafe { ptr::read(&this.inner) };
182
183        (inner, buf)
184    }
185}
186
187impl<W: ?Sized + Write> BufWriter<W> {
188    /// Send data in our local buffer into the inner writer, looping as
189    /// necessary until either it's all been sent or an error occurs.
190    ///
191    /// Because all the data in the buffer has been reported to our owner as
192    /// "successfully written" (by returning nonzero success values from
193    /// `write`), any 0-length writes from `inner` must be reported as i/o
194    /// errors from this method.
195    pub(in crate::io) fn flush_buf(&mut self) -> io::Result<()> {
196        /// Helper struct to ensure the buffer is updated after all the writes
197        /// are complete. It tracks the number of written bytes and drains them
198        /// all from the front of the buffer when dropped.
199        struct BufGuard<'a> {
200            buffer: &'a mut Vec<u8>,
201            written: usize,
202        }
203
204        impl<'a> BufGuard<'a> {
205            fn new(buffer: &'a mut Vec<u8>) -> Self {
206                Self { buffer, written: 0 }
207            }
208
209            /// The unwritten part of the buffer
210            fn remaining(&self) -> &[u8] {
211                &self.buffer[self.written..]
212            }
213
214            /// Flag some bytes as removed from the front of the buffer
215            fn consume(&mut self, amt: usize) {
216                self.written += amt;
217            }
218
219            /// true if all of the bytes have been written
220            fn done(&self) -> bool {
221                self.written >= self.buffer.len()
222            }
223        }
224
225        impl Drop for BufGuard<'_> {
226            fn drop(&mut self) {
227                if self.written > 0 {
228                    self.buffer.drain(..self.written);
229                }
230            }
231        }
232
233        let mut guard = BufGuard::new(&mut self.buf);
234        while !guard.done() {
235            self.panicked = true;
236            let r = self.inner.write(guard.remaining());
237            self.panicked = false;
238
239            match r {
240                Ok(0) => {
241                    return Err(io::const_error!(
242                        ErrorKind::WriteZero,
243                        "failed to write the buffered data",
244                    ));
245                }
246                Ok(n) => guard.consume(n),
247                Err(ref e) if e.is_interrupted() => {}
248                Err(e) => return Err(e),
249            }
250        }
251        Ok(())
252    }
253
254    /// Buffer some data without flushing it, regardless of the size of the
255    /// data. Writes as much as possible without exceeding capacity. Returns
256    /// the number of bytes written.
257    pub(super) fn write_to_buf(&mut self, buf: &[u8]) -> usize {
258        let available = self.spare_capacity();
259        let amt_to_buffer = available.min(buf.len());
260
261        // SAFETY: `amt_to_buffer` is <= buffer's spare capacity by construction.
262        unsafe {
263            self.write_to_buffer_unchecked(&buf[..amt_to_buffer]);
264        }
265
266        amt_to_buffer
267    }
268
269    /// Gets a reference to the underlying writer.
270    ///
271    /// # Examples
272    ///
273    /// ```no_run
274    /// use std::io::BufWriter;
275    /// use std::net::TcpStream;
276    ///
277    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
278    ///
279    /// // we can use reference just like buffer
280    /// let reference = buffer.get_ref();
281    /// ```
282    #[stable(feature = "rust1", since = "1.0.0")]
283    pub fn get_ref(&self) -> &W {
284        &self.inner
285    }
286
287    /// Gets a mutable reference to the underlying writer.
288    ///
289    /// It is inadvisable to directly write to the underlying writer.
290    ///
291    /// # Examples
292    ///
293    /// ```no_run
294    /// use std::io::BufWriter;
295    /// use std::net::TcpStream;
296    ///
297    /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
298    ///
299    /// // we can use reference just like buffer
300    /// let reference = buffer.get_mut();
301    /// ```
302    #[stable(feature = "rust1", since = "1.0.0")]
303    pub fn get_mut(&mut self) -> &mut W {
304        &mut self.inner
305    }
306
307    /// Returns a reference to the internally buffered data.
308    ///
309    /// # Examples
310    ///
311    /// ```no_run
312    /// use std::io::BufWriter;
313    /// use std::net::TcpStream;
314    ///
315    /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
316    ///
317    /// // See how many bytes are currently buffered
318    /// let bytes_buffered = buf_writer.buffer().len();
319    /// ```
320    #[stable(feature = "bufreader_buffer", since = "1.37.0")]
321    pub fn buffer(&self) -> &[u8] {
322        &self.buf
323    }
324
325    /// Returns a mutable reference to the internal buffer.
326    ///
327    /// This can be used to write data directly into the buffer without triggering writers
328    /// to the underlying writer.
329    ///
330    /// That the buffer is a `Vec` is an implementation detail.
331    /// Callers should not modify the capacity as there currently is no public API to do so
332    /// and thus any capacity changes would be unexpected by the user.
333    pub(in crate::io) fn buffer_mut(&mut self) -> &mut Vec<u8> {
334        &mut self.buf
335    }
336
337    /// Returns the number of bytes the internal buffer can hold without flushing.
338    ///
339    /// # Examples
340    ///
341    /// ```no_run
342    /// use std::io::BufWriter;
343    /// use std::net::TcpStream;
344    ///
345    /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
346    ///
347    /// // Check the capacity of the inner buffer
348    /// let capacity = buf_writer.capacity();
349    /// // Calculate how many bytes can be written without flushing
350    /// let without_flush = capacity - buf_writer.buffer().len();
351    /// ```
352    #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
353    pub fn capacity(&self) -> usize {
354        self.buf.capacity()
355    }
356
357    // Ensure this function does not get inlined into `write`, so that it
358    // remains inlineable and its common path remains as short as possible.
359    // If this function ends up being called frequently relative to `write`,
360    // it's likely a sign that the client is using an improperly sized buffer
361    // or their write patterns are somewhat pathological.
362    #[cold]
363    #[inline(never)]
364    fn write_cold(&mut self, buf: &[u8]) -> io::Result<usize> {
365        if buf.len() > self.spare_capacity() {
366            self.flush_buf()?;
367        }
368
369        // Why not len > capacity? To avoid a needless trip through the buffer when the input
370        // exactly fills it. We'd just need to flush it to the underlying writer anyway.
371        if buf.len() >= self.buf.capacity() {
372            self.panicked = true;
373            let r = self.get_mut().write(buf);
374            self.panicked = false;
375            r
376        } else {
377            // Write to the buffer. In this case, we write to the buffer even if it fills it
378            // exactly. Doing otherwise would mean flushing the buffer, then writing this
379            // input to the inner writer, which in many cases would be a worse strategy.
380
381            // SAFETY: There was either enough spare capacity already, or there wasn't and we
382            // flushed the buffer to ensure that there is. In the latter case, we know that there
383            // is because flushing ensured that our entire buffer is spare capacity, and we entered
384            // this block because the input buffer length is less than that capacity. In either
385            // case, it's safe to write the input buffer to our buffer.
386            unsafe {
387                self.write_to_buffer_unchecked(buf);
388            }
389
390            Ok(buf.len())
391        }
392    }
393
394    // Ensure this function does not get inlined into `write_all`, so that it
395    // remains inlineable and its common path remains as short as possible.
396    // If this function ends up being called frequently relative to `write_all`,
397    // it's likely a sign that the client is using an improperly sized buffer
398    // or their write patterns are somewhat pathological.
399    #[cold]
400    #[inline(never)]
401    fn write_all_cold(&mut self, buf: &[u8]) -> io::Result<()> {
402        // Normally, `write_all` just calls `write` in a loop. We can do better
403        // by calling `self.get_mut().write_all()` directly, which avoids
404        // round trips through the buffer in the event of a series of partial
405        // writes in some circumstances.
406
407        if buf.len() > self.spare_capacity() {
408            self.flush_buf()?;
409        }
410
411        // Why not len > capacity? To avoid a needless trip through the buffer when the input
412        // exactly fills it. We'd just need to flush it to the underlying writer anyway.
413        if buf.len() >= self.buf.capacity() {
414            self.panicked = true;
415            let r = self.get_mut().write_all(buf);
416            self.panicked = false;
417            r
418        } else {
419            // Write to the buffer. In this case, we write to the buffer even if it fills it
420            // exactly. Doing otherwise would mean flushing the buffer, then writing this
421            // input to the inner writer, which in many cases would be a worse strategy.
422
423            // SAFETY: There was either enough spare capacity already, or there wasn't and we
424            // flushed the buffer to ensure that there is. In the latter case, we know that there
425            // is because flushing ensured that our entire buffer is spare capacity, and we entered
426            // this block because the input buffer length is less than that capacity. In either
427            // case, it's safe to write the input buffer to our buffer.
428            unsafe {
429                self.write_to_buffer_unchecked(buf);
430            }
431
432            Ok(())
433        }
434    }
435
436    // SAFETY: Requires `buf.len() <= self.buf.capacity() - self.buf.len()`,
437    // i.e., that input buffer length is less than or equal to spare capacity.
438    #[inline]
439    unsafe fn write_to_buffer_unchecked(&mut self, buf: &[u8]) {
440        debug_assert!(buf.len() <= self.spare_capacity());
441        let old_len = self.buf.len();
442        let buf_len = buf.len();
443        let src = buf.as_ptr();
444        unsafe {
445            let dst = self.buf.as_mut_ptr().add(old_len);
446            ptr::copy_nonoverlapping(src, dst, buf_len);
447            self.buf.set_len(old_len + buf_len);
448        }
449    }
450
451    #[inline]
452    fn spare_capacity(&self) -> usize {
453        self.buf.capacity() - self.buf.len()
454    }
455}
456
457#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
458/// Error returned for the buffered data from `BufWriter::into_parts`, when the underlying
459/// writer has previously panicked.  Contains the (possibly partly written) buffered data.
460///
461/// # Example
462///
463/// ```
464/// use std::io::{self, BufWriter, Write};
465/// use std::panic::{catch_unwind, AssertUnwindSafe};
466///
467/// struct PanickingWriter;
468/// impl Write for PanickingWriter {
469///   fn write(&mut self, buf: &[u8]) -> io::Result<usize> { panic!() }
470///   fn flush(&mut self) -> io::Result<()> { panic!() }
471/// }
472///
473/// let mut stream = BufWriter::new(PanickingWriter);
474/// write!(stream, "some data").unwrap();
475/// let result = catch_unwind(AssertUnwindSafe(|| {
476///     stream.flush().unwrap()
477/// }));
478/// assert!(result.is_err());
479/// let (recovered_writer, buffered_data) = stream.into_parts();
480/// assert!(matches!(recovered_writer, PanickingWriter));
481/// assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data");
482/// ```
483pub struct WriterPanicked {
484    buf: Vec<u8>,
485}
486
487impl WriterPanicked {
488    /// Returns the perhaps-unwritten data.  Some of this data may have been written by the
489    /// panicking call(s) to the underlying writer, so simply writing it again is not a good idea.
490    #[must_use = "`self` will be dropped if the result is not used"]
491    #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
492    pub fn into_inner(self) -> Vec<u8> {
493        self.buf
494    }
495
496    const DESCRIPTION: &'static str =
497        "BufWriter inner writer panicked, what data remains unwritten is not known";
498}
499
500#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
501impl error::Error for WriterPanicked {
502    #[allow(deprecated, deprecated_in_future)]
503    fn description(&self) -> &str {
504        Self::DESCRIPTION
505    }
506}
507
508#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
509impl fmt::Display for WriterPanicked {
510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511        write!(f, "{}", Self::DESCRIPTION)
512    }
513}
514
515#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
516impl fmt::Debug for WriterPanicked {
517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518        f.debug_struct("WriterPanicked")
519            .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
520            .finish()
521    }
522}
523
524#[stable(feature = "rust1", since = "1.0.0")]
525impl<W: ?Sized + Write> Write for BufWriter<W> {
526    #[inline]
527    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
528        // Use < instead of <= to avoid a needless trip through the buffer in some cases.
529        // See `write_cold` for details.
530        if buf.len() < self.spare_capacity() {
531            // SAFETY: safe by above conditional.
532            unsafe {
533                self.write_to_buffer_unchecked(buf);
534            }
535
536            Ok(buf.len())
537        } else {
538            self.write_cold(buf)
539        }
540    }
541
542    #[inline]
543    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
544        // Use < instead of <= to avoid a needless trip through the buffer in some cases.
545        // See `write_all_cold` for details.
546        if buf.len() < self.spare_capacity() {
547            // SAFETY: safe by above conditional.
548            unsafe {
549                self.write_to_buffer_unchecked(buf);
550            }
551
552            Ok(())
553        } else {
554            self.write_all_cold(buf)
555        }
556    }
557
558    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
559        // FIXME: Consider applying `#[inline]` / `#[inline(never)]` optimizations already applied
560        // to `write` and `write_all`. The performance benefits can be significant. See #79930.
561        if self.get_ref().is_write_vectored() {
562            // We have to handle the possibility that the total length of the buffers overflows
563            // `usize` (even though this can only happen if multiple `IoSlice`s reference the
564            // same underlying buffer, as otherwise the buffers wouldn't fit in memory). If the
565            // computation overflows, then surely the input cannot fit in our buffer, so we forward
566            // to the inner writer's `write_vectored` method to let it handle it appropriately.
567            let mut saturated_total_len: usize = 0;
568
569            for buf in bufs {
570                saturated_total_len = saturated_total_len.saturating_add(buf.len());
571
572                if saturated_total_len > self.spare_capacity() && !self.buf.is_empty() {
573                    // Flush if the total length of the input exceeds our buffer's spare capacity.
574                    // If we would have overflowed, this condition also holds, and we need to flush.
575                    self.flush_buf()?;
576                }
577
578                if saturated_total_len >= self.buf.capacity() {
579                    // Forward to our inner writer if the total length of the input is greater than or
580                    // equal to our buffer capacity. If we would have overflowed, this condition also
581                    // holds, and we punt to the inner writer.
582                    self.panicked = true;
583                    let r = self.get_mut().write_vectored(bufs);
584                    self.panicked = false;
585                    return r;
586                }
587            }
588
589            // `saturated_total_len < self.buf.capacity()` implies that we did not saturate.
590
591            // SAFETY: We checked whether or not the spare capacity was large enough above. If
592            // it was, then we're safe already. If it wasn't, we flushed, making sufficient
593            // room for any input <= the buffer size, which includes this input.
594            unsafe {
595                bufs.iter().for_each(|b| self.write_to_buffer_unchecked(b));
596            };
597
598            Ok(saturated_total_len)
599        } else {
600            let mut iter = bufs.iter();
601            let mut total_written = if let Some(buf) = iter.by_ref().find(|&buf| !buf.is_empty()) {
602                // This is the first non-empty slice to write, so if it does
603                // not fit in the buffer, we still get to flush and proceed.
604                if buf.len() > self.spare_capacity() {
605                    self.flush_buf()?;
606                }
607                if buf.len() >= self.buf.capacity() {
608                    // The slice is at least as large as the buffering capacity,
609                    // so it's better to write it directly, bypassing the buffer.
610                    self.panicked = true;
611                    let r = self.get_mut().write(buf);
612                    self.panicked = false;
613                    return r;
614                } else {
615                    // SAFETY: We checked whether or not the spare capacity was large enough above.
616                    // If it was, then we're safe already. If it wasn't, we flushed, making
617                    // sufficient room for any input <= the buffer size, which includes this input.
618                    unsafe {
619                        self.write_to_buffer_unchecked(buf);
620                    }
621
622                    buf.len()
623                }
624            } else {
625                return Ok(0);
626            };
627            debug_assert!(total_written != 0);
628            for buf in iter {
629                if buf.len() <= self.spare_capacity() {
630                    // SAFETY: safe by above conditional.
631                    unsafe {
632                        self.write_to_buffer_unchecked(buf);
633                    }
634
635                    // This cannot overflow `usize`. If we are here, we've written all of the bytes
636                    // so far to our buffer, and we've ensured that we never exceed the buffer's
637                    // capacity. Therefore, `total_written` <= `self.buf.capacity()` <= `usize::MAX`.
638                    total_written += buf.len();
639                } else {
640                    break;
641                }
642            }
643            Ok(total_written)
644        }
645    }
646
647    fn is_write_vectored(&self) -> bool {
648        true
649    }
650
651    fn flush(&mut self) -> io::Result<()> {
652        self.flush_buf().and_then(|()| self.get_mut().flush())
653    }
654}
655
656#[stable(feature = "rust1", since = "1.0.0")]
657impl<W: ?Sized + Write> fmt::Debug for BufWriter<W>
658where
659    W: fmt::Debug,
660{
661    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
662        fmt.debug_struct("BufWriter")
663            .field("writer", &&self.inner)
664            .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
665            .finish()
666    }
667}
668
669#[stable(feature = "rust1", since = "1.0.0")]
670impl<W: ?Sized + Write + Seek> Seek for BufWriter<W> {
671    /// Seek to the offset, in bytes, in the underlying writer.
672    ///
673    /// Seeking always writes out the internal buffer before seeking.
674    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
675        self.flush_buf()?;
676        self.get_mut().seek(pos)
677    }
678}
679
680#[stable(feature = "rust1", since = "1.0.0")]
681impl<W: ?Sized + Write> Drop for BufWriter<W> {
682    fn drop(&mut self) {
683        if !self.panicked {
684            // dtors should not panic, so we ignore a failed flush
685            let _r = self.flush_buf();
686        }
687    }
688}