Skip to content

Commit 71aa691

Browse files
Thomasdezeeuwcramertj
authored andcommitted
Add AsyncReadTestExt::limited
As a partner to AsyncWriteTestExt::limited_write.
1 parent a4b26fe commit 71aa691

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

futures-test/src/io/limited.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,27 @@ impl<W: AsyncWrite> AsyncWrite for Limited<W> {
7676
self.io().poll_close(cx)
7777
}
7878
}
79+
80+
impl<R: AsyncRead> AsyncRead for Limited<R> {
81+
fn poll_read(
82+
mut self: Pin<&mut Self>,
83+
cx: &mut Context<'_>,
84+
buf: &mut [u8],
85+
) -> Poll<io::Result<usize>> {
86+
let limit = cmp::min(*self.as_mut().limit(), buf.len());
87+
self.io().poll_read(cx, &mut buf[..limit])
88+
}
89+
}
90+
91+
impl<R: AsyncBufRead> AsyncBufRead for Limited<R> {
92+
fn poll_fill_buf<'a>(
93+
self: Pin<&'a mut Self>,
94+
cx: &mut Context<'_>,
95+
) -> Poll<io::Result<&'a [u8]>> {
96+
self.io().poll_fill_buf(cx)
97+
}
98+
99+
fn consume(self: Pin<&mut Self>, amount: usize) {
100+
self.io().consume(amount)
101+
}
102+
}

futures-test/src/io/read/mod.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use futures_io::AsyncRead;
44

55
pub use super::interleave_pending::InterleavePending;
6+
pub use super::limited::Limited;
67

78
/// Additional combinators for testing async readers.
89
pub trait AsyncReadTestExt: AsyncRead {
@@ -72,6 +73,41 @@ pub trait AsyncReadTestExt: AsyncRead {
7273
{
7374
InterleavePending::new(self)
7475
}
76+
77+
/// Limit the number of bytes allowed to be read on each call to `poll_read`.
78+
///
79+
/// # Examples
80+
///
81+
/// ```
82+
/// #![feature(async_await)]
83+
/// use futures::task::Poll;
84+
/// use futures::io::AsyncRead;
85+
/// use futures_test::task::noop_context;
86+
/// use futures_test::io::AsyncReadTestExt;
87+
/// use pin_utils::pin_mut;
88+
///
89+
/// let reader = std::io::Cursor::new(&[1, 2, 3, 4, 5]).limited(2);
90+
/// pin_mut!(reader);
91+
///
92+
/// let mut cx = noop_context();
93+
///
94+
/// let mut buf = [0; 10];
95+
///
96+
/// assert_eq!(reader.as_mut().poll_read(&mut cx, &mut buf)?, Poll::Ready(2));
97+
/// assert_eq!(&buf[..2], &[1, 2]);
98+
/// assert_eq!(reader.as_mut().poll_read(&mut cx, &mut buf)?, Poll::Ready(2));
99+
/// assert_eq!(&buf[..2], &[3, 4]);
100+
/// assert_eq!(reader.as_mut().poll_read(&mut cx, &mut buf)?, Poll::Ready(1));
101+
/// assert_eq!(&buf[..1], &[5]);
102+
///
103+
/// # Ok::<(), std::io::Error>(())
104+
/// ```
105+
fn limited(self, limit: usize) -> Limited<Self>
106+
where
107+
Self: Sized,
108+
{
109+
Limited::new(self, limit)
110+
}
75111
}
76112

77113
impl<R> AsyncReadTestExt for R where R: AsyncRead {}

0 commit comments

Comments
 (0)