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 ] |
12 | async fn read_buf() { |
13 | struct Rd { |
14 | cnt: usize, |
15 | } |
16 | |
17 | impl AsyncRead for Rd { |
18 | fn poll_read( |
19 | mut self: Pin<&mut Self>, |
20 | _cx: &mut Context<'_>, |
21 | buf: &mut ReadBuf<'_>, |
22 | ) -> Poll<io::Result<()>> { |
23 | self.cnt += 1; |
24 | buf.put_slice(b"hello world" ); |
25 | Poll::Ready(Ok(())) |
26 | } |
27 | } |
28 | |
29 | let mut buf = vec![]; |
30 | let mut rd = Rd { cnt: 0 }; |
31 | |
32 | let n = assert_ok!(rd.read_buf(&mut buf).await); |
33 | assert_eq!(1, rd.cnt); |
34 | assert_eq!(n, 11); |
35 | assert_eq!(buf[..], b"hello world" [..]); |
36 | } |
37 | |
38 | #[tokio::test ] |
39 | #[cfg (feature = "io-util" )] |
40 | async fn issue_5588() { |
41 | use bytes::BufMut; |
42 | |
43 | // steps to zero |
44 | let mut buf = [0; 8]; |
45 | let mut read_buf = ReadBuf::new(&mut buf); |
46 | assert_eq!(read_buf.remaining_mut(), 8); |
47 | assert_eq!(read_buf.chunk_mut().len(), 8); |
48 | unsafe { |
49 | read_buf.advance_mut(1); |
50 | } |
51 | assert_eq!(read_buf.remaining_mut(), 7); |
52 | assert_eq!(read_buf.chunk_mut().len(), 7); |
53 | unsafe { |
54 | read_buf.advance_mut(5); |
55 | } |
56 | assert_eq!(read_buf.remaining_mut(), 2); |
57 | assert_eq!(read_buf.chunk_mut().len(), 2); |
58 | unsafe { |
59 | read_buf.advance_mut(2); |
60 | } |
61 | assert_eq!(read_buf.remaining_mut(), 0); |
62 | assert_eq!(read_buf.chunk_mut().len(), 0); |
63 | |
64 | // directly to zero |
65 | let mut buf = [0; 8]; |
66 | let mut read_buf = ReadBuf::new(&mut buf); |
67 | assert_eq!(read_buf.remaining_mut(), 8); |
68 | assert_eq!(read_buf.chunk_mut().len(), 8); |
69 | unsafe { |
70 | read_buf.advance_mut(8); |
71 | } |
72 | assert_eq!(read_buf.remaining_mut(), 0); |
73 | assert_eq!(read_buf.chunk_mut().len(), 0); |
74 | |
75 | // uninit |
76 | let mut buf = [std::mem::MaybeUninit::new(1); 8]; |
77 | let mut uninit = ReadBuf::uninit(&mut buf); |
78 | assert_eq!(uninit.remaining_mut(), 8); |
79 | assert_eq!(uninit.chunk_mut().len(), 8); |
80 | |
81 | let mut buf = [std::mem::MaybeUninit::uninit(); 8]; |
82 | let mut uninit = ReadBuf::uninit(&mut buf); |
83 | unsafe { |
84 | uninit.advance_mut(4); |
85 | } |
86 | assert_eq!(uninit.remaining_mut(), 4); |
87 | assert_eq!(uninit.chunk_mut().len(), 4); |
88 | uninit.put_u8(1); |
89 | assert_eq!(uninit.remaining_mut(), 3); |
90 | assert_eq!(uninit.chunk_mut().len(), 3); |
91 | uninit.put_slice(&[1, 2, 3]); |
92 | assert_eq!(uninit.remaining_mut(), 0); |
93 | assert_eq!(uninit.chunk_mut().len(), 0); |
94 | } |
95 | |