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