1 #![warn(rust_2018_idioms)]
2 #![cfg(all(feature = "full", not(target_os = "wasi")))] // Wasi does not support bind()
3
4 use std::time::Duration;
5 use tokio::io::{self, copy_bidirectional, AsyncReadExt, AsyncWriteExt};
6 use tokio::net::TcpStream;
7 use tokio::task::JoinHandle;
8
make_socketpair() -> (TcpStream, TcpStream)9 async fn make_socketpair() -> (TcpStream, TcpStream) {
10 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
11 let addr = listener.local_addr().unwrap();
12 let connector = TcpStream::connect(addr);
13 let acceptor = listener.accept();
14
15 let (c1, c2) = tokio::join!(connector, acceptor);
16
17 (c1.unwrap(), c2.unwrap().0)
18 }
19
block_write(s: &mut TcpStream) -> usize20 async fn block_write(s: &mut TcpStream) -> usize {
21 static BUF: [u8; 2048] = [0; 2048];
22
23 let mut copied = 0;
24 loop {
25 tokio::select! {
26 result = s.write(&BUF) => {
27 copied += result.expect("write error")
28 },
29 _ = tokio::time::sleep(Duration::from_millis(10)) => {
30 break;
31 }
32 }
33 }
34
35 copied
36 }
37
symmetric<F, Fut>(mut cb: F) where F: FnMut(JoinHandle<io::Result<(u64, u64)>>, TcpStream, TcpStream) -> Fut, Fut: std::future::Future<Output = ()>,38 async fn symmetric<F, Fut>(mut cb: F)
39 where
40 F: FnMut(JoinHandle<io::Result<(u64, u64)>>, TcpStream, TcpStream) -> Fut,
41 Fut: std::future::Future<Output = ()>,
42 {
43 // We run the test twice, with streams passed to copy_bidirectional in
44 // different orders, in order to ensure that the two arguments are
45 // interchangeable.
46
47 let (a, mut a1) = make_socketpair().await;
48 let (b, mut b1) = make_socketpair().await;
49
50 let handle = tokio::spawn(async move { copy_bidirectional(&mut a1, &mut b1).await });
51 cb(handle, a, b).await;
52
53 let (a, mut a1) = make_socketpair().await;
54 let (b, mut b1) = make_socketpair().await;
55
56 let handle = tokio::spawn(async move { copy_bidirectional(&mut b1, &mut a1).await });
57
58 cb(handle, b, a).await;
59 }
60
61 #[tokio::test]
62 #[cfg_attr(miri, ignore)] // No `socket` in miri.
test_basic_transfer()63 async fn test_basic_transfer() {
64 symmetric(|_handle, mut a, mut b| async move {
65 a.write_all(b"test").await.unwrap();
66 let mut tmp = [0; 4];
67 b.read_exact(&mut tmp).await.unwrap();
68 assert_eq!(&tmp[..], b"test");
69 })
70 .await
71 }
72
73 #[tokio::test]
74 #[cfg_attr(miri, ignore)] // No `socket` in miri.
test_transfer_after_close()75 async fn test_transfer_after_close() {
76 symmetric(|handle, mut a, mut b| async move {
77 AsyncWriteExt::shutdown(&mut a).await.unwrap();
78 b.read_to_end(&mut Vec::new()).await.unwrap();
79
80 b.write_all(b"quux").await.unwrap();
81 let mut tmp = [0; 4];
82 a.read_exact(&mut tmp).await.unwrap();
83 assert_eq!(&tmp[..], b"quux");
84
85 // Once both are closed, we should have our handle back
86 drop(b);
87
88 assert_eq!(handle.await.unwrap().unwrap(), (0, 4));
89 })
90 .await
91 }
92
93 #[tokio::test]
94 #[cfg_attr(miri, ignore)] // No `socket` in miri.
blocking_one_side_does_not_block_other()95 async fn blocking_one_side_does_not_block_other() {
96 symmetric(|handle, mut a, mut b| async move {
97 block_write(&mut a).await;
98
99 b.write_all(b"quux").await.unwrap();
100 let mut tmp = [0; 4];
101 a.read_exact(&mut tmp).await.unwrap();
102 assert_eq!(&tmp[..], b"quux");
103
104 AsyncWriteExt::shutdown(&mut a).await.unwrap();
105
106 let mut buf = Vec::new();
107 b.read_to_end(&mut buf).await.unwrap();
108
109 drop(b);
110
111 assert_eq!(handle.await.unwrap().unwrap(), (buf.len() as u64, 4));
112 })
113 .await
114 }
115
116 #[tokio::test]
immediate_exit_on_write_error()117 async fn immediate_exit_on_write_error() {
118 let payload = b"here, take this";
119 let error = || io::Error::new(io::ErrorKind::Other, "no thanks!");
120
121 let mut a = tokio_test::io::Builder::new()
122 .read(payload)
123 .write_error(error())
124 .build();
125
126 let mut b = tokio_test::io::Builder::new()
127 .read(payload)
128 .write_error(error())
129 .build();
130
131 assert!(copy_bidirectional(&mut a, &mut b).await.is_err());
132 }
133
134 #[tokio::test]
immediate_exit_on_read_error()135 async fn immediate_exit_on_read_error() {
136 let error = || io::Error::new(io::ErrorKind::Other, "got nothing!");
137
138 let mut a = tokio_test::io::Builder::new().read_error(error()).build();
139
140 let mut b = tokio_test::io::Builder::new().read_error(error()).build();
141
142 assert!(copy_bidirectional(&mut a, &mut b).await.is_err());
143 }
144
145 #[tokio::test]
copy_bidirectional_is_cooperative()146 async fn copy_bidirectional_is_cooperative() {
147 tokio::select! {
148 biased;
149 _ = async {
150 loop {
151 let payload = b"here, take this";
152
153 let mut a = tokio_test::io::Builder::new()
154 .read(payload)
155 .write(payload)
156 .build();
157
158 let mut b = tokio_test::io::Builder::new()
159 .read(payload)
160 .write(payload)
161 .build();
162
163 let _ = copy_bidirectional(&mut a, &mut b).await;
164 }
165 } => {},
166 _ = tokio::task::yield_now() => {}
167 }
168 }
169