/
io_async_read.rs
114 lines (94 loc) · 2.6 KB
/
io_async_read.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#![allow(clippy::transmute_ptr_to_ptr)]
#![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
use tokio::io::{AsyncRead, ReadBuf};
use tokio_test::task;
use tokio_test::{assert_ready_err, assert_ready_ok};
use bytes::BytesMut;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
#[test]
fn assert_obj_safe() {
fn _assert<T>() {}
_assert::<Box<dyn AsyncRead>>();
}
#[test]
fn read_buf_success() {
struct Rd;
impl AsyncRead for Rd {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
buf.append(b"hello world");
Poll::Ready(Ok(()))
}
}
let mut buf = BytesMut::with_capacity(65);
task::spawn(Rd).enter(|cx, rd| {
let n = assert_ready_ok!(rd.poll_read_buf(cx, &mut buf));
assert_eq!(11, n);
assert_eq!(buf[..], b"hello world"[..]);
});
}
#[test]
fn read_buf_error() {
struct Rd;
impl AsyncRead for Rd {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let err = io::ErrorKind::Other.into();
Poll::Ready(Err(err))
}
}
let mut buf = BytesMut::with_capacity(65);
task::spawn(Rd).enter(|cx, rd| {
let err = assert_ready_err!(rd.poll_read_buf(cx, &mut buf));
assert_eq!(err.kind(), io::ErrorKind::Other);
});
}
#[test]
fn read_buf_no_capacity() {
struct Rd;
impl AsyncRead for Rd {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
unimplemented!();
}
}
let mut buf = [0u8; 0];
task::spawn(Rd).enter(|cx, rd| {
let n = assert_ready_ok!(rd.poll_read_buf(cx, &mut &mut buf[..]));
assert_eq!(0, n);
});
}
#[test]
fn read_buf_uninitialized_ok() {
struct Rd;
impl AsyncRead for Rd {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
assert_eq!(buf.remaining(), 64);
assert_eq!(buf.filled().len(), 0);
assert_eq!(buf.initialized().len(), 0);
Poll::Ready(Ok(()))
}
}
// Can't create BytesMut w/ zero capacity, so fill it up
let mut buf = BytesMut::with_capacity(64);
task::spawn(Rd).enter(|cx, rd| {
let n = assert_ready_ok!(rd.poll_read_buf(cx, &mut buf));
assert_eq!(0, n);
});
}