diff options
Diffstat (limited to 'ctr-std/src/io/impls.rs')
| -rw-r--r-- | ctr-std/src/io/impls.rs | 47 |
1 files changed, 44 insertions, 3 deletions
diff --git a/ctr-std/src/io/impls.rs b/ctr-std/src/io/impls.rs index 6b26c01..fe1179a 100644 --- a/ctr-std/src/io/impls.rs +++ b/ctr-std/src/io/impls.rs @@ -9,7 +9,7 @@ // except according to those terms. use cmp; -use io::{self, SeekFrom, Read, Write, Seek, BufRead, Error, ErrorKind}; +use io::{self, SeekFrom, Read, Initializer, Write, Seek, BufRead, Error, ErrorKind}; use fmt; use mem; @@ -24,6 +24,11 @@ impl<'a, R: Read + ?Sized> Read for &'a mut R { } #[inline] + unsafe fn initializer(&self) -> Initializer { + (**self).initializer() + } + + #[inline] fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_to_end(buf) } @@ -88,6 +93,11 @@ impl<R: Read + ?Sized> Read for Box<R> { } #[inline] + unsafe fn initializer(&self) -> Initializer { + (**self).initializer() + } + + #[inline] fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_to_end(buf) } @@ -157,22 +167,53 @@ impl<'a> Read for &'a [u8] { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let amt = cmp::min(buf.len(), self.len()); let (a, b) = self.split_at(amt); - buf[..amt].copy_from_slice(a); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if amt == 1 { + buf[0] = a[0]; + } else { + buf[..amt].copy_from_slice(a); + } + *self = b; Ok(amt) } #[inline] + unsafe fn initializer(&self) -> Initializer { + Initializer::nop() + } + + #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { if buf.len() > self.len() { return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")); } let (a, b) = self.split_at(buf.len()); - buf.copy_from_slice(a); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if buf.len() == 1 { + buf[0] = a[0]; + } else { + buf.copy_from_slice(a); + } + *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")] |