Skip to content

Commit

Permalink
Rollup merge of rust-lang#45083 - fhartwig:slice-read-to-end, r=bluss
Browse files Browse the repository at this point in the history
Add read_to_end implementation to &[u8]'s Read impl

The default impl for read_to_end does a bunch of bookkeeping
that isn't necessary for slices and is about 4 times slower
on my machine.

The following benchmark takes about 30 ns before this change and about 7 ns after:

```
#[bench]
fn bench_read_std(b: &mut Bencher) {
    let data = vec![0u8; 100];
    let mut v = Vec::with_capacity(200);
    b.iter(|| {
        let mut s = data.as_slice();
        v.clear();
        s.read_to_end(&mut v).unwrap();
    });
}
```

This solves the easy part of  rust-lang#44819 (I think extending this to `Take<&[u8]> `would require specialization)
  • Loading branch information
kennytm authored Oct 8, 2017
2 parents db202e3 + d52acbe commit 262612c
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/libstd/io/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ impl<'a> Read for &'a [u8] {
*self = b;
Ok(())
}

#[inline]
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
buf.extend_from_slice(*self);
let len = self.len();
*self = &self[len..];
Ok(len)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down

0 comments on commit 262612c

Please sign in to comment.