Skip to content

Optimize creation of buffered readers/writers #10424

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
Nov 12, 2013
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
15 changes: 13 additions & 2 deletions src/libstd/rt/io/buffered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,17 @@ pub struct BufferedReader<R> {
impl<R: Reader> BufferedReader<R> {
/// Creates a new `BufferedReader` with 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 { vec::raw::set_len(&mut buf, cap); }
BufferedReader {
inner: inner,
buf: vec::from_elem(cap, 0u8),
buf: buf,
pos: 0,
cap: 0
}
Expand Down Expand Up @@ -183,9 +191,12 @@ pub struct BufferedWriter<W> {
impl<W: Writer> BufferedWriter<W> {
/// Creates a new `BufferedWriter` with 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.
let mut buf = vec::with_capacity(cap);
unsafe { vec::raw::set_len(&mut buf, cap); }
BufferedWriter {
inner: inner,
buf: vec::from_elem(cap, 0u8),
buf: buf,
pos: 0
}
}
Expand Down