Skip to content

Commit 01e7018

Browse files
committed
BufWriter: improve safety comment
1 parent 0f29dc4 commit 01e7018

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

Diff for: library/std/src/io/buffered/bufwriter.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -366,9 +366,11 @@ impl<W: Write> BufWriter<W> {
366366
// exactly. Doing otherwise would mean flushing the buffer, then writing this
367367
// input to the inner writer, which in many cases would be a worse strategy.
368368

369-
// SAFETY: We just called `self.flush_buf()`, so `self.buf.len()` is 0, and
370-
// we entered this else block because `buf.len() < self.buf.capacity()`.
371-
// Therefore, `buf.len() <= self.buf.capacity() - self.buf.len()`.
369+
// SAFETY: There was either enough spare capacity already, or there wasn't and we
370+
// flushed the buffer to ensure that there is. In the latter case, we know that there
371+
// is because flushing ensured that our entire buffer is spare capacity, and we entered
372+
// this block because the input buffer length is less than that capacity. In either
373+
// case, it's safe to write the input buffer to our buffer.
372374
unsafe {
373375
self.write_to_buffer_unchecked(buf);
374376
}
@@ -406,9 +408,11 @@ impl<W: Write> BufWriter<W> {
406408
// exactly. Doing otherwise would mean flushing the buffer, then writing this
407409
// input to the inner writer, which in many cases would be a worse strategy.
408410

409-
// SAFETY: We just called `self.flush_buf()`, so `self.buf.len()` is 0, and
410-
// we entered this else block because `buf.len() < self.buf.capacity()`.
411-
// Therefore, `buf.len() <= self.buf.capacity() - self.buf.len()`.
411+
// SAFETY: There was either enough spare capacity already, or there wasn't and we
412+
// flushed the buffer to ensure that there is. In the latter case, we know that there
413+
// is because flushing ensured that our entire buffer is spare capacity, and we entered
414+
// this block because the input buffer length is less than that capacity. In either
415+
// case, it's safe to write the input buffer to our buffer.
412416
unsafe {
413417
self.write_to_buffer_unchecked(buf);
414418
}

0 commit comments

Comments
 (0)