diff --git a/library/std/src/io/impls.rs b/library/std/src/io/impls.rs index e5048dcc8acd9..7511438b02bad 100644 --- a/library/std/src/io/impls.rs +++ b/library/std/src/io/impls.rs @@ -9,6 +9,7 @@ use crate::io::{ self, BorrowedCursor, BufRead, ErrorKind, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write, }; use crate::mem; +use crate::str; // ============================================================================= // Forwarding implementations @@ -307,6 +308,17 @@ impl Read for &[u8] { *self = &self[len..]; Ok(len) } + + #[inline] + fn read_to_string(&mut self, buf: &mut String) -> io::Result { + let content = str::from_utf8(self).map_err(|_| { + io::const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8") + })?; + buf.push_str(content); + let len = self.len(); + *self = &self[len..]; + Ok(len) + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -434,6 +446,33 @@ impl Read for VecDeque { self.drain(..n); Ok(()) } + + #[inline] + fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { + // The total len is known upfront so we can reserve it in a single call. + let len = self.len(); + buf.reserve(len); + + let (front, back) = self.as_slices(); + buf.extend_from_slice(front); + buf.extend_from_slice(back); + self.clear(); + Ok(len) + } + + #[inline] + fn read_to_string(&mut self, buf: &mut String) -> io::Result { + // We have to use a single contiguous slice because the `VecDequeue` might be split in the + // middle of an UTF-8 character. + let len = self.len(); + let content = self.make_contiguous(); + let string = str::from_utf8(content).map_err(|_| { + io::const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8") + })?; + buf.push_str(string); + self.clear(); + Ok(len) + } } /// Write is implemented for `VecDeque` by appending to the `VecDeque`, growing it as needed. @@ -445,6 +484,21 @@ impl Write for VecDeque { Ok(buf.len()) } + #[inline] + fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { + let len = bufs.iter().map(|b| b.len()).sum(); + self.reserve(len); + for buf in bufs { + self.extend(&**buf); + } + Ok(len) + } + + #[inline] + fn is_write_vectored(&self) -> bool { + true + } + #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.extend(buf);