1 #![warn(rust_2018_idioms)]
2 #![cfg(feature = "full")]
3 
4 use tokio::io::{AsyncRead, AsyncReadExt, ReadBuf};
5 use tokio_test::assert_ok;
6 
7 use std::io;
8 use std::pin::Pin;
9 use std::task::{Context, Poll};
10 
11 #[tokio::test]
read()12 async fn read() {
13     #[derive(Default)]
14     struct Rd {
15         poll_cnt: usize,
16     }
17 
18     impl AsyncRead for Rd {
19         fn poll_read(
20             mut self: Pin<&mut Self>,
21             _cx: &mut Context<'_>,
22             buf: &mut ReadBuf<'_>,
23         ) -> Poll<io::Result<()>> {
24             assert_eq!(0, self.poll_cnt);
25             self.poll_cnt += 1;
26 
27             buf.put_slice(b"hello world");
28             Poll::Ready(Ok(()))
29         }
30     }
31 
32     let mut buf = Box::new([0; 11]);
33     let mut rd = Rd::default();
34 
35     let n = assert_ok!(rd.read(&mut buf[..]).await);
36     assert_eq!(n, 11);
37     assert_eq!(buf[..], b"hello world"[..]);
38 }
39 
40 struct BadAsyncRead;
41 
42 impl AsyncRead for BadAsyncRead {
poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>>43     fn poll_read(
44         self: Pin<&mut Self>,
45         _cx: &mut Context<'_>,
46         buf: &mut ReadBuf<'_>,
47     ) -> Poll<io::Result<()>> {
48         *buf = ReadBuf::new(Box::leak(vec![0; buf.capacity()].into_boxed_slice()));
49         buf.advance(buf.capacity());
50         Poll::Ready(Ok(()))
51     }
52 }
53 
54 #[tokio::test]
55 #[should_panic]
read_buf_bad_async_read()56 async fn read_buf_bad_async_read() {
57     let mut buf = Vec::with_capacity(10);
58     BadAsyncRead.read_buf(&mut buf).await.unwrap();
59 }
60