From 89f1848b556971a4278f2b2385137ca6c9e07094 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 12 Jan 2015 19:50:33 -0800 Subject: [PATCH] Initialize memory for BufferedReader buffer 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. --- src/libstd/io/buffered.rs | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 36def48b88b32..9aee90132155b 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -15,7 +15,7 @@ use cmp; use fmt; use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult}; -use iter::{IteratorExt, ExactSizeIterator}; +use iter::{IteratorExt, ExactSizeIterator, repeat}; use ops::Drop; use option::Option; use option::Option::{Some, None}; @@ -62,17 +62,11 @@ impl fmt::Show for BufferedReader where R: fmt::Show { impl BufferedReader { /// Creates a new `BufferedReader` with the specified buffer capacity pub fn with_capacity(cap: uint, inner: R) -> BufferedReader { - // It's *much* faster to create an uninitialized buffer than it is to - // fill everything in with 0. This buffer is entirely an implementation - // detail and is never exposed, so we're safe to not initialize - // everything up-front. This allows creation of BufferedReader instances - // to be very cheap (large mallocs are not nearly as expensive as large - // callocs). - let mut buf = Vec::with_capacity(cap); - unsafe { buf.set_len(cap); } BufferedReader { inner: inner, - buf: buf, + // We can't use the same trick here as we do for BufferedWriter, + // since this memory is visible to the inner Reader. + buf: repeat(0).take(cap).collect(), pos: 0, cap: 0, } @@ -166,7 +160,12 @@ impl fmt::Show for BufferedWriter where W: fmt::Show { impl BufferedWriter { /// Creates a new `BufferedWriter` with the specified buffer capacity pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter { - // See comments in BufferedReader for why this uses unsafe code. + // It's *much* faster to create an uninitialized buffer than it is to + // fill everything in with 0. This buffer is entirely an implementation + // detail and is never exposed, so we're safe to not initialize + // everything up-front. This allows creation of BufferedWriter instances + // to be very cheap (large mallocs are not nearly as expensive as large + // callocs). let mut buf = Vec::with_capacity(cap); unsafe { buf.set_len(cap); } BufferedWriter {