Skip to content

Commit 674dd62

Browse files
committed
Reduce branching in write_vectored for BufWriter
Do what write does and optimize for the most likely case: slices are much smaller than the buffer. If a slice does not fit completely in the remaining capacity of the buffer, it is left out rather than buffered partially. Special treatment is only left for oversized slices that are written directly to the underlying writer.
1 parent 00deeb3 commit 674dd62

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

library/std/src/io/buffered/bufwriter.rs

+9-14
Original file line numberDiff line numberDiff line change
@@ -343,9 +343,8 @@ impl<W: Write> Write for BufWriter<W> {
343343
Ok(total_len)
344344
}
345345
} else {
346-
let mut total_written = 0;
347346
let mut iter = bufs.iter();
348-
if let Some(buf) = iter.by_ref().find(|&buf| !buf.is_empty()) {
347+
let mut total_written = if let Some(buf) = iter.by_ref().find(|&buf| !buf.is_empty()) {
349348
// This is the first non-empty slice to write, so if it does
350349
// not fit in the buffer, we still get to flush and proceed.
351350
if self.buf.len() + buf.len() > self.buf.capacity() {
@@ -360,22 +359,18 @@ impl<W: Write> Write for BufWriter<W> {
360359
return r;
361360
} else {
362361
self.buf.extend_from_slice(buf);
363-
total_written += buf.len();
362+
buf.len()
364363
}
365-
debug_assert!(total_written != 0);
366-
}
364+
} else {
365+
return Ok(0);
366+
};
367+
debug_assert!(total_written != 0);
367368
for buf in iter {
368-
if buf.len() >= self.buf.capacity() {
369-
// This slice should be written directly, but we have
370-
// already buffered some of the input. Bail out,
371-
// expecting it to be handled as the first slice in the
372-
// next call to write_vectored.
369+
if self.buf.len() + buf.len() > self.buf.capacity() {
373370
break;
374371
} else {
375-
total_written += self.write_to_buf(buf);
376-
if self.buf.capacity() == self.buf.len() {
377-
break;
378-
}
372+
self.buf.extend_from_slice(buf);
373+
total_written += buf.len();
379374
}
380375
}
381376
Ok(total_written)

0 commit comments

Comments
 (0)