Skip to content

Initialize memory for BufferedReader buffer #21076

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 14, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions src/libstd/io/buffered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -62,17 +62,11 @@ impl<R> fmt::Show for BufferedReader<R> where R: fmt::Show {
impl<R: Reader> BufferedReader<R> {
/// Creates a new `BufferedReader` with the specified buffer capacity
pub fn with_capacity(cap: uint, inner: R) -> BufferedReader<R> {
// 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,
}
Expand Down Expand Up @@ -166,7 +160,12 @@ impl<W> fmt::Show for BufferedWriter<W> where W: fmt::Show {
impl<W: Writer> BufferedWriter<W> {
/// Creates a new `BufferedWriter` with the specified buffer capacity
pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter<W> {
// 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 {
Expand Down