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 20, 2024
1 parent caf520a commit 2e7308d
Show file tree
Hide file tree
Showing 2 changed files with 52 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
37 changes: 34 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,37 @@ fn test_vec_deque() {
assert_eq!(b"world piece", &out[..]);
}

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

buffer.extend(b"hello world");
buffer.drain(.."hello ".len());
buffer.extend(b" hello again it's working!");

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());
assert!(b"world hello again it's working!".starts_with(&chunks[0]));

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>>();
assert_eq!(combined, b"world hello again it's working!");

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 2e7308d

Please sign in to comment.