Skip to content

Commit f14ccdb

Browse files
authored
Rollup merge of #95632 - evanrichter:master, r=joshtriplett
impl Read and Write for VecDeque<u8> Implementing `Read` and `Write` for `VecDeque<u8>` fills in the VecDeque api surface where `Vec<u8>` and `Cursor<Vec<u8>>` already impl Read and Write. Not only for completeness, but VecDeque in particular is a very handy mock interface for a TCP echo service, if only it supported Read/Write. Since this PR is just an impl trait, I don't think there is a way to limit it behind a feature flag, so it's "insta-stable". Please correct me if I'm wrong here, not trying to rush stability.
2 parents 6dc598a + 8b7a3f4 commit f14ccdb

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

library/std/src/io/impls.rs

+48
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ mod tests;
33

44
use crate::alloc::Allocator;
55
use crate::cmp;
6+
use crate::collections::VecDeque;
67
use crate::fmt;
78
use crate::io::{
89
self, BufRead, ErrorKind, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, Write,
@@ -410,3 +411,50 @@ impl<A: Allocator> Write for Vec<u8, A> {
410411
Ok(())
411412
}
412413
}
414+
415+
/// Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`.
416+
#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
417+
impl<A: Allocator> Read for VecDeque<u8, A> {
418+
/// Fill `buf` with the contents of the "front" slice as returned by
419+
/// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
420+
/// discontiguous, multiple calls to `read` will be needed to read the entire content.
421+
#[inline]
422+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
423+
let (ref mut front, _) = self.as_slices();
424+
let n = Read::read(front, buf)?;
425+
self.drain(..n);
426+
Ok(n)
427+
}
428+
429+
#[inline]
430+
fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
431+
let (ref mut front, _) = self.as_slices();
432+
let n = cmp::min(buf.remaining(), front.len());
433+
Read::read_buf(front, buf)?;
434+
self.drain(..n);
435+
Ok(())
436+
}
437+
}
438+
439+
/// Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed.
440+
#[stable(feature = "vecdeque_read_write", since = "1.63.0")]
441+
impl<A: Allocator> Write for VecDeque<u8, A> {
442+
#[inline]
443+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
444+
self.reserve(buf.len());
445+
self.extend(buf);
446+
Ok(buf.len())
447+
}
448+
449+
#[inline]
450+
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
451+
self.reserve(buf.len());
452+
self.extend(buf);
453+
Ok(())
454+
}
455+
456+
#[inline]
457+
fn flush(&mut self) -> io::Result<()> {
458+
Ok(())
459+
}
460+
}

0 commit comments

Comments
 (0)