Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specialize some io::Read and io::Write methods for VecDeque<u8> and &[u8] #110608

Merged
merged 1 commit into from
Apr 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions library/std/src/io/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<usize> {
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")]
Expand Down Expand Up @@ -434,6 +446,33 @@ impl<A: Allocator> Read for VecDeque<u8, A> {
self.drain(..n);
Ok(())
}

#[inline]
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
// 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<usize> {
// 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<u8>` by appending to the `VecDeque`, growing it as needed.
Expand All @@ -445,6 +484,21 @@ impl<A: Allocator> Write for VecDeque<u8, A> {
Ok(buf.len())
}

#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
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);
Expand Down