Skip to content

Commit

Permalink
Merge pull request #599 from hyperium/zero-buf
Browse files Browse the repository at this point in the history
perf(buffer): zero out buffers using memset instead of iter().take()
  • Loading branch information
seanmonstar committed Jul 8, 2015
2 parents 46e0aa0 + 0e7db69 commit 18a29ac
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::cmp;
use std::iter;
use std::io::{self, Read, BufRead};

pub struct BufReader<R> {
Expand All @@ -21,7 +20,9 @@ impl<R: Read> BufReader<R> {
#[inline]
pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> {
let mut buf = Vec::with_capacity(cap);
buf.extend(iter::repeat(0).take(cap));
unsafe {
grow_zerofill(&mut buf, cap);
}
BufReader {
inner: rdr,
buf: buf,
Expand Down Expand Up @@ -71,11 +72,19 @@ impl<R: Read> BufReader<R> {
self.buf.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap);
let new = self.buf.capacity() - self.buf.len();
trace!("reserved {}", new);
self.buf.extend(iter::repeat(0).take(new));
unsafe { grow_zerofill(&mut self.buf, new) }
}
}
}

#[inline]
unsafe fn grow_zerofill(buf: &mut Vec<u8>, additional: usize) {
use std::ptr;
let len = buf.len();
buf.set_len(len + additional);
ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len());
}

impl<R: Read> Read for BufReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.cap == self.pos && buf.len() >= self.buf.len() {
Expand Down

0 comments on commit 18a29ac

Please sign in to comment.