1 #![warn(rust_2018_idioms)]
2 #![cfg(feature = "full")]
3 
4 use std::pin::Pin;
5 use std::task::{Context, Poll};
6 use tokio::io::{AsyncRead, AsyncReadExt, ReadBuf};
7 use tokio_test::assert_ok;
8 
9 #[tokio::test]
read_to_end()10 async fn read_to_end() {
11     let mut buf = vec![];
12     let mut rd: &[u8] = b"hello world";
13 
14     let n = assert_ok!(rd.read_to_end(&mut buf).await);
15     assert_eq!(n, 11);
16     assert_eq!(buf[..], b"hello world"[..]);
17 }
18 
19 #[derive(Copy, Clone, Debug)]
20 enum State {
21     Initializing,
22     JustFilling,
23     Done,
24 }
25 
26 struct UninitTest {
27     num_init: usize,
28     state: State,
29 }
30 
31 impl AsyncRead for UninitTest {
poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<std::io::Result<()>>32     fn poll_read(
33         self: Pin<&mut Self>,
34         _cx: &mut Context<'_>,
35         buf: &mut ReadBuf<'_>,
36     ) -> Poll<std::io::Result<()>> {
37         let me = Pin::into_inner(self);
38         let real_num_init = buf.initialized().len() - buf.filled().len();
39         assert_eq!(real_num_init, me.num_init, "{:?}", me.state);
40 
41         match me.state {
42             State::Initializing => {
43                 buf.initialize_unfilled_to(me.num_init + 2);
44                 buf.advance(1);
45                 me.num_init += 1;
46 
47                 if me.num_init == 24 {
48                     me.state = State::JustFilling;
49                 }
50             }
51             State::JustFilling => {
52                 buf.advance(1);
53                 me.num_init -= 1;
54 
55                 if me.num_init == 15 {
56                     // The buffer is resized on next call.
57                     me.num_init = 0;
58                     me.state = State::Done;
59                 }
60             }
61             State::Done => { /* .. do nothing .. */ }
62         }
63 
64         Poll::Ready(Ok(()))
65     }
66 }
67 
68 #[tokio::test]
read_to_end_uninit()69 async fn read_to_end_uninit() {
70     let mut buf = Vec::with_capacity(64);
71     let mut test = UninitTest {
72         num_init: 0,
73         state: State::Initializing,
74     };
75 
76     test.read_to_end(&mut buf).await.unwrap();
77     assert_eq!(buf.len(), 33);
78 }
79