Skip to content

Commit d52398e

Browse files
committed
auto merge of #21076 : sfackler/rust/bufferedreader-undef, r=Gankro
It's passed to the underlying reader, so uninitialized memory == sad times. We might want to shrink the default buffer size as well. 64k is pretty huge. Java uses 8k by default, and Go uses 4k for reference. r? @alexcrichton
2 parents 3614e1d + 89f1848 commit d52398e

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

Diff for: src/libstd/io/buffered.rs

+10-11
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
use cmp;
1616
use fmt;
1717
use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult};
18-
use iter::{IteratorExt, ExactSizeIterator};
18+
use iter::{IteratorExt, ExactSizeIterator, repeat};
1919
use ops::Drop;
2020
use option::Option;
2121
use option::Option::{Some, None};
@@ -62,17 +62,11 @@ impl<R> fmt::Show for BufferedReader<R> where R: fmt::Show {
6262
impl<R: Reader> BufferedReader<R> {
6363
/// Creates a new `BufferedReader` with the specified buffer capacity
6464
pub fn with_capacity(cap: uint, inner: R) -> BufferedReader<R> {
65-
// It's *much* faster to create an uninitialized buffer than it is to
66-
// fill everything in with 0. This buffer is entirely an implementation
67-
// detail and is never exposed, so we're safe to not initialize
68-
// everything up-front. This allows creation of BufferedReader instances
69-
// to be very cheap (large mallocs are not nearly as expensive as large
70-
// callocs).
71-
let mut buf = Vec::with_capacity(cap);
72-
unsafe { buf.set_len(cap); }
7365
BufferedReader {
7466
inner: inner,
75-
buf: buf,
67+
// We can't use the same trick here as we do for BufferedWriter,
68+
// since this memory is visible to the inner Reader.
69+
buf: repeat(0).take(cap).collect(),
7670
pos: 0,
7771
cap: 0,
7872
}
@@ -166,7 +160,12 @@ impl<W> fmt::Show for BufferedWriter<W> where W: fmt::Show {
166160
impl<W: Writer> BufferedWriter<W> {
167161
/// Creates a new `BufferedWriter` with the specified buffer capacity
168162
pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter<W> {
169-
// See comments in BufferedReader for why this uses unsafe code.
163+
// It's *much* faster to create an uninitialized buffer than it is to
164+
// fill everything in with 0. This buffer is entirely an implementation
165+
// detail and is never exposed, so we're safe to not initialize
166+
// everything up-front. This allows creation of BufferedWriter instances
167+
// to be very cheap (large mallocs are not nearly as expensive as large
168+
// callocs).
170169
let mut buf = Vec::with_capacity(cap);
171170
unsafe { buf.set_len(cap); }
172171
BufferedWriter {

0 commit comments

Comments
 (0)