1 #![warn(rust_2018_idioms)]
2 #![cfg(feature = "full")]
3
4 use tokio::io::{AsyncRead, AsyncReadExt};
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 [u8],
23 ) -> Poll<io::Result<usize>> {
24 assert_eq!(0, self.poll_cnt);
25 self.poll_cnt += 1;
26
27 buf[0..11].copy_from_slice(b"hello world");
28 Poll::Ready(Ok(11))
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 [u8], ) -> Poll<io::Result<usize>>43 fn poll_read(
44 self: Pin<&mut Self>,
45 _cx: &mut Context<'_>,
46 buf: &mut [u8],
47 ) -> Poll<io::Result<usize>> {
48 for b in &mut *buf {
49 *b = b'a';
50 }
51 Poll::Ready(Ok(buf.len() * 2))
52 }
53 }
54
55 #[tokio::test]
56 #[should_panic]
read_buf_bad_async_read()57 async fn read_buf_bad_async_read() {
58 let mut buf = Vec::with_capacity(10);
59 BadAsyncRead.read_buf(&mut buf).await.unwrap();
60 }
61