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