Skip to content

Commit

Permalink
auto merge of #18108 : mahkoh/rust/buffered_reader, r=alexcrichton
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
bors committed Oct 20, 2014
2 parents aff4f11 + 3839696 commit 045bc28
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/libstd/io/buffered.rs
Original file line number Diff line number Diff line change
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

0 comments on commit 045bc28

Please sign in to comment.