1 mod mock_reader {
2 use futures::io::AsyncRead;
3 use std::io;
4 use std::pin::Pin;
5 use std::task::{Context, Poll};
6
7 pub struct MockReader {
8 fun: Box<dyn FnMut(&mut [u8]) -> Poll<io::Result<usize>>>,
9 }
10
11 impl MockReader {
new(fun: impl FnMut(&mut [u8]) -> Poll<io::Result<usize>> + 'static) -> Self12 pub fn new(fun: impl FnMut(&mut [u8]) -> Poll<io::Result<usize>> + 'static) -> Self {
13 Self { fun: Box::new(fun) }
14 }
15 }
16
17 impl AsyncRead for MockReader {
poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut [u8] ) -> Poll<io::Result<usize>>18 fn poll_read(
19 self: Pin<&mut Self>,
20 _cx: &mut Context<'_>,
21 buf: &mut [u8]
22 ) -> Poll<io::Result<usize>> {
23 (self.get_mut().fun)(buf)
24 }
25 }
26 }
27
28 /// Verifies that the default implementation of `poll_read_vectored`
29 /// calls `poll_read` with an empty slice if no buffers are provided.
30 #[test]
read_vectored_no_buffers()31 fn read_vectored_no_buffers() {
32 use futures::io::AsyncRead;
33 use futures_test::task::panic_context;
34 use std::io;
35 use std::pin::Pin;
36 use std::task::Poll;
37
38 use mock_reader::MockReader;
39
40 let mut reader = MockReader::new(|buf| {
41 assert_eq!(buf, b"");
42 Err(io::ErrorKind::BrokenPipe.into()).into()
43 });
44 let cx = &mut panic_context();
45 let bufs = &mut [];
46
47 let res = Pin::new(&mut reader).poll_read_vectored(cx, bufs);
48 let res = res.map_err(|e| e.kind());
49 assert_eq!(res, Poll::Ready(Err(io::ErrorKind::BrokenPipe)))
50 }
51
52 /// Verifies that the default implementation of `poll_read_vectored`
53 /// calls `poll_read` with the first non-empty buffer.
54 #[test]
read_vectored_first_non_empty()55 fn read_vectored_first_non_empty() {
56 use futures::io::AsyncRead;
57 use futures_test::task::panic_context;
58 use std::io;
59 use std::pin::Pin;
60 use std::task::Poll;
61
62 use mock_reader::MockReader;
63
64 let mut reader = MockReader::new(|buf| {
65 assert_eq!(buf.len(), 4);
66 buf.copy_from_slice(b"four");
67 Poll::Ready(Ok(4))
68 });
69 let cx = &mut panic_context();
70 let mut buf = [0; 4];
71 let bufs = &mut [
72 io::IoSliceMut::new(&mut []),
73 io::IoSliceMut::new(&mut []),
74 io::IoSliceMut::new(&mut buf),
75 ];
76
77 let res = Pin::new(&mut reader).poll_read_vectored(cx, bufs);
78 let res = res.map_err(|e| e.kind());
79 assert_eq!(res, Poll::Ready(Ok(4)));
80 assert_eq!(buf, b"four"[..]);
81 }
82