Add Read::initializer.

This is an API that allows types to indicate that they can be passed
buffers of uninitialized memory which can improve performance.
This commit is contained in:
Steven Fackler
2017-05-14 21:29:18 -04:00
parent 445077963c
commit ecbb896b9e
28 changed files with 222 additions and 269 deletions

View File

@@ -11,7 +11,8 @@
#![allow(missing_copy_implementations)]
use fmt;
use io::{self, Read, Write, ErrorKind, BufRead};
use io::{self, Read, Initializer, Write, ErrorKind, BufRead};
use mem;
/// Copies the entire contents of a reader into a writer.
///
@@ -47,7 +48,12 @@ use io::{self, Read, Write, ErrorKind, BufRead};
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
where R: Read, W: Write
{
let mut buf = [0; super::DEFAULT_BUF_SIZE];
let mut buf = unsafe {
let mut buf: [u8; super::DEFAULT_BUF_SIZE] = mem::uninitialized();
reader.initializer().initialize(&mut buf);
buf
};
let mut written = 0;
loop {
let len = match reader.read(&mut buf) {
@@ -90,11 +96,19 @@ pub fn empty() -> Empty { Empty { _priv: () } }
#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Empty {
#[inline]
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
#[inline]
unsafe fn initializer(&self) -> Initializer {
Initializer::nop()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BufRead for Empty {
#[inline]
fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
#[inline]
fn consume(&mut self, _n: usize) {}
}
@@ -133,12 +147,18 @@ pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
#[stable(feature = "rust1", since = "1.0.0")]
impl Read for Repeat {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
for slot in &mut *buf {
*slot = self.byte;
}
Ok(buf.len())
}
#[inline]
unsafe fn initializer(&self) -> Initializer {
Initializer::nop()
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
@@ -176,7 +196,9 @@ pub fn sink() -> Sink { Sink { _priv: () } }
#[stable(feature = "rust1", since = "1.0.0")]
impl Write for Sink {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
#[inline]
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}