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