From 8b7a3f4d53f9e96a49d77ed42d22baf4d7743b94 Mon Sep 17 00:00:00 2001 From: Evan Richter Date: Tue, 17 May 2022 00:53:06 -0500 Subject: [PATCH] impl Read and Write for VecDeque * For read and read_buf, only the front slice of a discontiguous VecDeque is copied. The VecDeque is advanced after reading, making any back slice available for reading with a second call to Read::read(_buf). * For write, the VecDeque always appends the entire slice to the end, growing its allocation when necessary. --- library/std/src/io/impls.rs | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/library/std/src/io/impls.rs b/library/std/src/io/impls.rs index 64d2457bce159..0ca58efe1fe2f 100644 --- a/library/std/src/io/impls.rs +++ b/library/std/src/io/impls.rs @@ -3,6 +3,7 @@ mod tests; use crate::alloc::Allocator; use crate::cmp; +use crate::collections::VecDeque; use crate::fmt; use crate::io::{ self, BufRead, ErrorKind, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, Write, @@ -410,3 +411,50 @@ impl Write for Vec { Ok(()) } } + +/// Read is implemented for `VecDeque` by consuming bytes from the front of the `VecDeque`. +#[stable(feature = "vecdeque_read_write", since = "1.63.0")] +impl Read for VecDeque { + /// Fill `buf` with the contents of the "front" slice as returned by + /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are + /// discontiguous, multiple calls to `read` will be needed to read the entire content. + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let (ref mut front, _) = self.as_slices(); + let n = Read::read(front, buf)?; + self.drain(..n); + Ok(n) + } + + #[inline] + fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> { + let (ref mut front, _) = self.as_slices(); + let n = cmp::min(buf.remaining(), front.len()); + Read::read_buf(front, buf)?; + self.drain(..n); + Ok(()) + } +} + +/// Write is implemented for `VecDeque` by appending to the `VecDeque`, growing it as needed. +#[stable(feature = "vecdeque_read_write", since = "1.63.0")] +impl Write for VecDeque { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + self.reserve(buf.len()); + self.extend(buf); + Ok(buf.len()) + } + + #[inline] + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + self.reserve(buf.len()); + self.extend(buf); + Ok(()) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +}