Skip to content

Commit

Permalink
Add SeekBuf trait impl to Take
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanplecki committed Jan 27, 2024
1 parent 31142d3 commit d0515dc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
22 changes: 21 additions & 1 deletion src/buf/take.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Buf, Bytes};
use crate::{Buf, Bytes, SeekBuf};

use core::cmp;

Expand Down Expand Up @@ -153,3 +153,23 @@ impl<T: Buf> Buf for Take<T> {
r
}
}

impl<T: SeekBuf> SeekBuf for Take<T> {
fn chunk_from(&self, start: usize) -> Option<&[u8]> {
if start < self.limit {
let remaining = self.limit - start;
let chunk = self.inner.chunk_from(start)?;
Some(&chunk[..chunk.len().min(remaining)])
} else {
None
}
}

fn chunk_to(&self, end: usize) -> Option<&[u8]> {
if end <= self.limit {
self.inner.chunk_to(end)
} else {
None
}
}
}
15 changes: 14 additions & 1 deletion tests/test_take.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![warn(rust_2018_idioms)]

use bytes::buf::Buf;
use bytes::Bytes;
use bytes::{Bytes, SeekBuf};

#[test]
fn long_take() {
Expand All @@ -12,6 +12,19 @@ fn long_take() {
assert_eq!(b"hello world", buf.chunk());
}

#[test]
fn take_from_seek_buf() {
let buf = b"hello world".take(5);

assert_eq!(buf.chunk_from(0), Some(b"hello".as_slice()));
assert_eq!(buf.chunk_from(3), Some(b"lo".as_slice()));
assert_eq!(buf.chunk_to(5), Some(b"hello".as_slice()));
assert_eq!(buf.chunk_to(2), Some(b"he".as_slice()));

assert_eq!(buf.chunk_from(6), None);
assert_eq!(buf.chunk_to(6), None);
}

#[test]
fn take_copy_to_bytes() {
let mut abcd = Bytes::copy_from_slice(b"abcd");
Expand Down

0 comments on commit d0515dc

Please sign in to comment.