1 #![warn(rust_2018_idioms)]
2 #![cfg(feature = "full")]
3 
4 use std::io::Result;
5 use std::io::{Read, Write};
6 use std::{net, thread};
7 
8 use tokio::io::{AsyncReadExt, AsyncWriteExt};
9 use tokio::net::TcpStream;
10 
11 #[tokio::test]
split() -> Result<()>12 async fn split() -> Result<()> {
13     const MSG: &[u8] = b"split";
14 
15     let listener = net::TcpListener::bind("127.0.0.1:0")?;
16     let addr = listener.local_addr()?;
17 
18     let handle = thread::spawn(move || {
19         let (mut stream, _) = listener.accept().unwrap();
20         stream.write_all(MSG).unwrap();
21 
22         let mut read_buf = [0u8; 32];
23         let read_len = stream.read(&mut read_buf).unwrap();
24         assert_eq!(&read_buf[..read_len], MSG);
25     });
26 
27     let mut stream = TcpStream::connect(&addr).await?;
28     let (mut read_half, mut write_half) = stream.split();
29 
30     let mut read_buf = [0u8; 32];
31     let peek_len1 = read_half.peek(&mut read_buf[..]).await?;
32     let peek_len2 = read_half.peek(&mut read_buf[..]).await?;
33     assert_eq!(peek_len1, peek_len2);
34 
35     let read_len = read_half.read(&mut read_buf[..]).await?;
36     assert_eq!(peek_len1, read_len);
37     assert_eq!(&read_buf[..read_len], MSG);
38 
39     write_half.write(MSG).await?;
40     handle.join().unwrap();
41     Ok(())
42 }
43