Skip to content

Commit

Permalink
Implement chunks_vectored for VecDeque<u8>
Browse files Browse the repository at this point in the history
  • Loading branch information
paolobarbolini committed May 22, 2024
1 parent caf520a commit 52c6b7f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
18 changes: 18 additions & 0 deletions src/buf/vec_deque.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use alloc::collections::VecDeque;
#[cfg(feature = "std")]
use std::io;

use super::Buf;

Expand All @@ -16,6 +18,22 @@ impl Buf for VecDeque<u8> {
}
}

#[cfg(feature = "std")]
fn chunks_vectored<'a>(&'a self, dst: &mut [io::IoSlice<'a>]) -> usize {
if self.is_empty() || dst.is_empty() {
return 0;
}

let (s1, s2) = self.as_slices();
dst[0] = io::IoSlice::new(s1);
if s2.is_empty() || dst.len() == 1 {
return 1;
}

dst[1] = io::IoSlice::new(s2);
2
}

fn advance(&mut self, cnt: usize) {
self.drain(..cnt);
}
Expand Down
41 changes: 38 additions & 3 deletions tests/test_buf.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#![warn(rust_2018_idioms)]

use std::collections::VecDeque;

use bytes::Buf;
#[cfg(feature = "std")]
use std::io::IoSlice;
Expand Down Expand Up @@ -58,9 +60,7 @@ fn test_bufs_vec() {

#[test]
fn test_vec_deque() {
use std::collections::VecDeque;

let mut buffer: VecDeque<u8> = VecDeque::new();
let mut buffer = VecDeque::new();
buffer.extend(b"hello world");
assert_eq!(11, buffer.remaining());
assert_eq!(b"hello world", buffer.chunk());
Expand All @@ -72,6 +72,41 @@ fn test_vec_deque() {
assert_eq!(b"world piece", &out[..]);
}

#[cfg(feature = "std")]
#[test]
fn test_vec_deque_vectored() {
let mut buffer = VecDeque::new();
buffer.reserve_exact(128);
assert_eq!(buffer.chunks_vectored(&mut [IoSlice::new(&[])]), 0);

buffer.extend(0..64);
buffer.drain(..32);
buffer.extend(64..150);

assert_eq!(buffer.chunks_vectored(&mut []), 0);

let mut chunks = [IoSlice::new(&[]); 1];
assert_eq!(buffer.chunks_vectored(&mut chunks), 1);
assert!(!chunks[0].is_empty());
let combined = chunks[0].iter().copied().collect::<Vec<u8>>();
let expected = (32..150).take(chunks[0].len()).collect::<Vec<_>>();
assert_eq!(combined, expected);

let mut chunks = [IoSlice::new(&[]); 2];
assert_eq!(buffer.chunks_vectored(&mut chunks), 2);
assert!(!chunks[0].is_empty());
assert!(!chunks[1].is_empty());
let combined = chunks
.iter()
.flat_map(|chunk| chunk.iter())
.copied()
.collect::<Vec<u8>>();
let expected = (32..150).collect::<Vec<u8>>();
assert_eq!(combined, expected);

assert_eq!(buffer.chunks_vectored(&mut [IoSlice::new(&[]); 8]), 2);
}

#[allow(unused_allocation)] // This is intentional.
#[test]
fn test_deref_buf_forwards() {
Expand Down

0 comments on commit 52c6b7f

Please sign in to comment.