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 unsafe {
474 let dst = self.buf.as_mut_ptr().add(old_len);
475 ptr::copy_nonoverlapping(src, dst, buf_len);
476 self.buf.set_len(old_len + buf_len);
477 }
478 }
479
480 #[inline]
481 fn spare_capacity(&self) -> usize {
482 self.buf.capacity() - self.buf.len()
483 }
484}
485
486#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
487/// Error returned for the buffered data from `BufWriter::into_parts`, when the underlying
488/// writer has previously panicked. Contains the (possibly partly written) buffered data.
489///
490/// # Example
491///
492/// ```
493/// use std::io::{self, BufWriter, Write};
494/// use std::panic::{catch_unwind, AssertUnwindSafe};
495///
496/// struct PanickingWriter;
497/// impl Write for PanickingWriter {
498/// fn write(&mut self, buf: &[u8]) -> io::Result<usize> { panic!() }
499/// fn flush(&mut self) -> io::Result<()> { panic!() }
500/// }
501///
502/// let mut stream = BufWriter::new(PanickingWriter);
503/// write!(stream, "some data").unwrap();
504/// let result = catch_unwind(AssertUnwindSafe(|| {
505/// stream.flush().unwrap()
506/// }));
507/// assert!(result.is_err());
508/// let (recovered_writer, buffered_data) = stream.into_parts();
509/// assert!(matches!(recovered_writer, PanickingWriter));
510/// assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data");
511/// ```
512pub struct WriterPanicked {
513 buf: Vec<u8>,
514}
515
516impl WriterPanicked {
517 /// Returns the perhaps-unwritten data. Some of this data may have been written by the
518 /// panicking call(s) to the underlying writer, so simply writing it again is not a good idea.
519 #[must_use = "`self` will be dropped if the result is not used"]
520 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
521 pub fn into_inner(self) -> Vec<u8> {
522 self.buf
523 }
524}
525
526#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
527impl error::Error for WriterPanicked {}
528
529#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
530impl fmt::Display for WriterPanicked {
531 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532 "BufWriter inner writer panicked, what data remains unwritten is not known".fmt(f)
533 }
534}
535
536#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
537impl fmt::Debug for WriterPanicked {
538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539 f.debug_struct("WriterPanicked")
540 .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
541 .finish()
542 }
543}
544
545#[stable(feature = "rust1", since = "1.0.0")]
546impl<W: ?Sized + Write> Write for BufWriter<W> {
547 #[inline]
548 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
549 // Use < instead of <= to avoid a needless trip through the buffer in some cases.
550 // See `write_cold` for details.
551 if buf.len() < self.spare_capacity() {
552 // SAFETY: safe by above conditional.
553 unsafe {
554 self.write_to_buffer_unchecked(buf);
555 }
556
557 Ok(buf.len())
558 } else {
559 self.write_cold(buf)
560 }
561 }
562
563 #[inline]
564 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
565 // Use < instead of <= to avoid a needless trip through the buffer in some cases.
566 // See `write_all_cold` for details.
567 if buf.len() < self.spare_capacity() {
568 // SAFETY: safe by above conditional.
569 unsafe {
570 self.write_to_buffer_unchecked(buf);
571 }
572
573 Ok(())
574 } else {
575 self.write_all_cold(buf)
576 }
577 }
578
579 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
580 // FIXME: Consider applying `#[inline]` / `#[inline(never)]` optimizations already applied
581 // to `write` and `write_all`. The performance benefits can be significant. See #79930.
582 if self.get_ref().is_write_vectored() {
583 // We have to handle the possibility that the total length of the buffers overflows
584 // `usize` (even though this can only happen if multiple `IoSlice`s reference the
585 // same underlying buffer, as otherwise the buffers wouldn't fit in memory). If the
586 // computation overflows, then surely the input cannot fit in our buffer, so we forward
587 // to the inner writer's `write_vectored` method to let it handle it appropriately.
588 let mut saturated_total_len: usize = 0;
589
590 for buf in bufs {
591 saturated_total_len = saturated_total_len.saturating_add(buf.len());
592
593 if saturated_total_len > self.spare_capacity() && !self.buf.is_empty() {
594 // Flush if the total length of the input exceeds our buffer's spare capacity.
595 // If we would have overflowed, this condition also holds, and we need to flush.
596 self.flush_buf()?;
597 }
598
599 if saturated_total_len >= self.buf.capacity() {
600 // Forward to our inner writer if the total length of the input is greater than or
601 // equal to our buffer capacity. If we would have overflowed, this condition also
602 // holds, and we punt to the inner writer.
603 self.panicked = true;
604 let r = self.get_mut().write_vectored(bufs);
605 self.panicked = false;
606 return r;
607 }
608 }
609
610 // `saturated_total_len < self.buf.capacity()` implies that we did not saturate.
611
612 // SAFETY: We checked whether or not the spare capacity was large enough above. If
613 // it was, then we're safe already. If it wasn't, we flushed, making sufficient
614 // room for any input <= the buffer size, which includes this input.
615 unsafe {
616 bufs.iter().for_each(|b| self.write_to_buffer_unchecked(b));
617 };
618
619 Ok(saturated_total_len)
620 } else {
621 let mut iter = bufs.iter();
622 let mut total_written = if let Some(buf) = iter.by_ref().find(|&buf| !buf.is_empty()) {
623 // This is the first non-empty slice to write, so if it does
624 // not fit in the buffer, we still get to flush and proceed.
625 if buf.len() > self.spare_capacity() {
626 self.flush_buf()?;
627 }
628 if buf.len() >= self.buf.capacity() {
629 // The slice is at least as large as the buffering capacity,
630 // so it's better to write it directly, bypassing the buffer.
631 self.panicked = true;
632 let r = self.get_mut().write(buf);
633 self.panicked = false;
634 return r;
635 } else {
636 // SAFETY: We checked whether or not the spare capacity was large enough above.
637 // If it was, then we're safe already. If it wasn't, we flushed, making
638 // sufficient room for any input <= the buffer size, which includes this input.
639 unsafe {
640 self.write_to_buffer_unchecked(buf);
641 }
642
643 buf.len()
644 }
645 } else {
646 return Ok(0);
647 };
648 debug_assert!(total_written != 0);
649 for buf in iter {
650 if buf.len() <= self.spare_capacity() {
651 // SAFETY: safe by above conditional.
652 unsafe {
653 self.write_to_buffer_unchecked(buf);
654 }
655
656 // This cannot overflow `usize`. If we are here, we've written all of the bytes
657 // so far to our buffer, and we've ensured that we never exceed the buffer's
658 // capacity. Therefore, `total_written` <= `self.buf.capacity()` <= `usize::MAX`.
659 total_written += buf.len();
660 } else {
661 break;
662 }
663 }
664 Ok(total_written)
665 }
666 }
667
668 fn is_write_vectored(&self) -> bool {
669 true
670 }
671
672 fn flush(&mut self) -> io::Result<()> {
673 self.flush_buf()?;
674 self.get_mut().flush()
675 }
676}
677
678#[stable(feature = "rust1", since = "1.0.0")]
679impl<W: ?Sized + Write> fmt::Debug for BufWriter<W>
680where
681 W: fmt::Debug,
682{
683 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
684 fmt.debug_struct("BufWriter")
685 .field("writer", &&self.inner)
686 .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
687 .finish()
688 }
689}
690
691#[stable(feature = "rust1", since = "1.0.0")]
692impl<W: ?Sized + Write + Seek> Seek for BufWriter<W> {
693 /// Seek to the offset, in bytes, in the underlying writer.
694 ///
695 /// Seeking always writes out the internal buffer before seeking.
696 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
697 self.flush_buf()?;
698 self.get_mut().seek(pos)
699 }
700}
701
702#[stable(feature = "rust1", since = "1.0.0")]
703impl<W: ?Sized + Write> Drop for BufWriter<W> {
704 fn drop(&mut self) {
705 if !self.panicked {
706 // dtors should not panic, so we ignore a failed flush
707 let _r = self.flush_buf();
708 }
709 }
710}