Skip to content

Commit

Permalink
Optimize BufferedReader::read for large buffers.
Browse files Browse the repository at this point in the history
This optimizes `read` for the case in which the number of bytes
requested is larger than the internal buffer. Note that the first
comparison occurs again right afterwards and should thus be free. The
second comparison occurs only in the cold branch.
  • Loading branch information
Julian Orth committed Oct 19, 2014
1 parent 1868a26 commit 3839696
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/libstd/io/buffered.rs
Expand Up @@ -104,6 +104,9 @@ impl<R: Reader> Buffer for BufferedReader<R> {

impl<R: Reader> Reader for BufferedReader<R> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
if self.pos == self.cap && buf.len() >= self.buf.capacity() {
return self.inner.read(buf);
}
let nread = {
let available = try!(self.fill_buf());
let nread = cmp::min(available.len(), buf.len());
Expand Down Expand Up @@ -409,13 +412,19 @@ mod test {

#[test]
fn test_buffered_reader() {
let inner = MemReader::new(vec!(0, 1, 2, 3, 4));
let inner = MemReader::new(vec!(5, 6, 7, 0, 1, 2, 3, 4));
let mut reader = BufferedReader::with_capacity(2, inner);

let mut buf = [0, 0, 0];
let nread = reader.read(buf);
assert_eq!(Ok(3), nread);
let b: &[_] = &[5, 6, 7];
assert_eq!(buf.as_slice(), b);

let mut buf = [0, 0];
let nread = reader.read(buf);
assert_eq!(Ok(2), nread);
let b: &[_] = &[0, 1, 0];
let b: &[_] = &[0, 1];
assert_eq!(buf.as_slice(), b);

let mut buf = [0];
Expand Down

6 comments on commit 3839696

@sfackler
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

r=alexcrichton

@bors
Copy link
Contributor

@bors bors commented on 3839696 Oct 20, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from alexcrichton
at mahkoh@3839696

@bors
Copy link
Contributor

@bors bors commented on 3839696 Oct 20, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging mahkoh/rust/buffered_reader = 3839696 into auto

@bors
Copy link
Contributor

@bors bors commented on 3839696 Oct 20, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mahkoh/rust/buffered_reader = 3839696 merged ok, testing candidate = 045bc28

@bors
Copy link
Contributor

@bors bors commented on 3839696 Oct 20, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on 3839696 Oct 20, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = 045bc28

Please sign in to comment.