Skip to content

Commit 1e6a7b4

Browse files
committed
Specialize some io::Read and io::Write methods for VecDeque<u8> and &[u8]
1 parent 7e23d18 commit 1e6a7b4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

library/std/src/io/impls.rs

+54
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::io::{
99
self, BorrowedCursor, BufRead, ErrorKind, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write,
1010
};
1111
use crate::mem;
12+
use crate::str;
1213

1314
// =============================================================================
1415
// Forwarding implementations
@@ -307,6 +308,17 @@ impl Read for &[u8] {
307308
*self = &self[len..];
308309
Ok(len)
309310
}
311+
312+
#[inline]
313+
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
314+
let content = str::from_utf8(self).map_err(|_| {
315+
io::const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8")
316+
})?;
317+
buf.push_str(content);
318+
let len = self.len();
319+
*self = &self[len..];
320+
Ok(len)
321+
}
310322
}
311323

312324
#[stable(feature = "rust1", since = "1.0.0")]
@@ -434,6 +446,33 @@ impl<A: Allocator> Read for VecDeque<u8, A> {
434446
self.drain(..n);
435447
Ok(())
436448
}
449+
450+
#[inline]
451+
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
452+
// The total len is known upfront so we can reserve it in a single call.
453+
let len = self.len();
454+
buf.reserve(len);
455+
456+
let (front, back) = self.as_slices();
457+
buf.extend_from_slice(front);
458+
buf.extend_from_slice(back);
459+
self.clear();
460+
Ok(len)
461+
}
462+
463+
#[inline]
464+
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
465+
// We have to use a single contiguous slice because the `VecDequeue` might be split in the
466+
// middle of an UTF-8 character.
467+
let len = self.len();
468+
let content = self.make_contiguous();
469+
let string = str::from_utf8(content).map_err(|_| {
470+
io::const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8")
471+
})?;
472+
buf.push_str(string);
473+
self.clear();
474+
Ok(len)
475+
}
437476
}
438477

439478
/// Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed.
@@ -445,6 +484,21 @@ impl<A: Allocator> Write for VecDeque<u8, A> {
445484
Ok(buf.len())
446485
}
447486

487+
#[inline]
488+
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
489+
let len = bufs.iter().map(|b| b.len()).sum();
490+
self.reserve(len);
491+
for buf in bufs {
492+
self.extend(&**buf);
493+
}
494+
Ok(len)
495+
}
496+
497+
#[inline]
498+
fn is_write_vectored(&self) -> bool {
499+
true
500+
}
501+
448502
#[inline]
449503
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
450504
self.extend(buf);

0 commit comments

Comments
 (0)