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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//! The byte streams' calls, on the handle and on a shared reference to it:
//! `AsyncRead` and `AsyncWrite`, the reads and writes that lend the driver
//! a buffer of the caller's (and for TCP, the zero-copy write), readiness,
//! the reads and writes that do not wait, and a stream's halves. A read
//! side, a write side and a stream (both, with its halves) each have their
//! macro: a socket stream takes all three, a pipe's end one side.
//!
//! Ready means the handle's own buffers: readable once a read would end at
//! once (bytes read ahead, the end of the stream, or an error, which the
//! read reports), writable once a write would be taken at once (room in the
//! write-behind, or an error).
use core::pin::Pin;
use core::task::{Context, Poll};
use std::io;
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::sync::Arc;
use futures_io::{AsyncRead, AsyncWrite};
use super::Released;
use super::split::{OwnedReadHalf, OwnedWriteHalf, ReadHalf, WriteHalf};
use crate::buf::owned::{IoBuf, IoBufMut, OwnedBuf};
use crate::buf::vectored::{self, IoVecBuf, IoVecBufMut};
use crate::io::{Handle, Interest, Ready};
/// The read side of a byte stream handle.
macro_rules! read_side {
($($ty:ty),* $(,)?) => {$(
impl Handle<$ty> {
/// Reads into the spare capacity of `buf`, after the bytes it
/// holds, and gives `buf` back with how many bytes came: zero at
/// the end of the stream, or when `buf` has no spare capacity.
/// The driver reads into `buf` itself, so the bytes are never
/// copied.
///
/// If the future is dropped before it completes, bytes the
/// driver read into `buf` stay with the handle for its next
/// read, so none is lost. `buf` is any
/// [`IoBufMut`](crate::io::IoBufMut).
pub async fn read_owned<B>(&self, buf: B) -> (io::Result<usize>, B)
where
B: IoBufMut,
{
self.source().read_owned(buf).await
}
/// Reads into the spare capacity of `bufs`, after the bytes each
/// holds, filling each buffer's room before the next one's, and
/// gives `bufs` back with how many bytes came: zero at the end of
/// the stream, or when no buffer has spare capacity. One read of
/// the kernel takes every room at once (`readv`, a `recvmsg` of
/// several buffers, a `WSARecv` of several `WSABUF`s), as
/// [`read_owned`](Self::read_owned) lends one buffer: the bytes
/// land in the buffers themselves, never copied. Bytes another
/// read left behind are copied in instead, in the same order.
pub async fn read_vectored_owned<V>(&self, bufs: V) -> (io::Result<usize>, V)
where
V: IoVecBufMut,
{
let bufs = OwnedBuf::vectored_read(vectored::filled(bufs));
let (result, bufs) = self.source().read_owned(bufs).await;
(result, vectored::into_filled(bufs.into_segments()))
}
/// Waits until a read would end at once.
///
/// # Errors
///
/// When the stream cannot be watched.
pub async fn readable(&self) -> io::Result<()> {
core::future::poll_fn(|cx| self.poll_read_ready(cx)).await
}
/// Polls until a read would end at once.
///
/// # Errors
///
/// When the stream cannot be watched.
pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.source().poll_read_ready(cx).map(|r| r.map(drop))
}
/// Reads what came ahead into `buf` without waiting; zero at the
/// end of the stream.
///
/// # Errors
///
/// `WouldBlock` when nothing came yet (the driver goes on reading,
/// so a later call finds what comes), and as `read(2)`.
pub fn try_read(&self, buf: &mut [u8]) -> io::Result<usize> {
super::at_once(|cx| self.source().poll_read(cx, buf, false))
}
/// Reads what came ahead into `bufs` without waiting, as
/// [`try_read`](Self::try_read).
///
/// # Errors
///
/// As [`try_read`](Self::try_read).
pub fn try_read_vectored(&self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
super::at_once(|cx| self.source().poll_read_vectored(cx, bufs))
}
}
impl AsyncRead for &Handle<$ty> {
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.source().poll_read(cx, buf, false)
}
#[inline]
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [io::IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
self.source().poll_read_vectored(cx, bufs)
}
}
impl AsyncRead for Handle<$ty> {
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.source().poll_read(cx, buf, false)
}
#[inline]
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [io::IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
self.source().poll_read_vectored(cx, bufs)
}
}
)*};
}
/// The write side of a byte stream handle.
macro_rules! write_side {
($($ty:ty),* $(,)?) => {$(
impl Handle<$ty> {
/// Writes all of `buf` and gives it back with its length. The
/// driver writes from `buf` itself, so the bytes are never
/// copied, and the write ends once the kernel took the last of
/// them.
///
/// If the future is dropped before it completes, the stream
/// gets `buf` whole or not at all: a write none of which went
/// out is withdrawn, and one that started is finished by the
/// driver. On Windows a TCP write is always finished: there a
/// cancelled send may have handed bytes to the stack while it
/// says it took none. `buf` is any [`IoBuf`](crate::io::IoBuf).
pub async fn write_owned<B>(&self, buf: B) -> (io::Result<usize>, B)
where
B: IoBuf,
{
self.source().write_owned(buf).await
}
/// Writes all of the bytes of `bufs`, each buffer's in order, as
/// one write, and gives `bufs` back with how many bytes that was.
/// No other write of the stream comes between two of them. Each
/// call of the kernel takes every buffer left at once (`writev`,
/// a `sendmsg` of several buffers, a `WSASend` of several
/// `WSABUF`s), from the buffers themselves, never copied; a call
/// the kernel takes part of goes on from the first byte it did
/// not take. If the future is dropped, as with
/// [`write_owned`](Self::write_owned): the stream gets all of the
/// bytes or none of them.
pub async fn write_vectored_owned<V>(&self, bufs: V) -> (io::Result<usize>, V)
where
V: IoVecBuf,
{
let bufs = OwnedBuf::vectored(vectored::written(bufs));
let (result, bufs) = self.source().write_owned(bufs).await;
(result, vectored::into_written(bufs.into_segments()))
}
/// Waits until a write would be taken at once.
///
/// # Errors
///
/// When the stream cannot be watched.
pub async fn writable(&self) -> io::Result<()> {
core::future::poll_fn(|cx| self.poll_write_ready(cx)).await
}
/// Polls until a write would be taken at once.
///
/// # Errors
///
/// When the stream cannot be watched.
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.source().poll_write_ready(cx).map(|r| r.map(drop))
}
/// Hands `buf` to the write-behind without waiting; returns how
/// many bytes it took.
///
/// # Errors
///
/// `WouldBlock` when the write-behind has no room, and the error
/// that stopped earlier bytes.
pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
super::at_once(|cx| self.source().poll_write_behind(cx, &[io::IoSlice::new(buf)]))
}
/// Hands the bytes of `bufs`, in order, to the write-behind
/// without waiting, as [`try_write`](Self::try_write).
///
/// # Errors
///
/// As [`try_write`](Self::try_write).
pub fn try_write_vectored(&self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
super::at_once(|cx| self.source().poll_write_behind(cx, bufs))
}
}
impl AsyncWrite for &Handle<$ty> {
#[inline]
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
self.source().poll_write(cx, buf)
}
#[inline]
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<io::Result<usize>> {
self.source().poll_write_vectored(cx, bufs)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.source().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.source().poll_close(cx)
}
}
impl AsyncWrite for Handle<$ty> {
#[inline]
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
self.source().poll_write(cx, buf)
}
#[inline]
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<io::Result<usize>> {
self.source().poll_write_vectored(cx, bufs)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.source().poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.source().poll_close(cx)
}
}
)*};
}
/// A stream that both reads and writes: its readiness of either, and its
/// halves.
macro_rules! stream_io {
($($ty:ty),* $(,)?) => {$(
read_side!($ty);
write_side!($ty);
impl Handle<$ty> {
/// The stream's two halves, borrowed: to read on one task and
/// write on another. Nothing is allocated.
pub fn split(&self) -> (ReadHalf<'_, $ty>, WriteHalf<'_, $ty>) {
(ReadHalf(self), WriteHalf(self))
}
/// The stream's two halves, owning it together; see
/// [`OwnedReadHalf::reunite`].
pub fn into_split(self) -> (OwnedReadHalf<$ty>, OwnedWriteHalf<$ty>) {
let both = Arc::new(self);
(OwnedReadHalf(Arc::clone(&both)), OwnedWriteHalf(both))
}
/// Waits until some of `interest` is ready, and says what is.
///
/// # Errors
///
/// When the stream cannot be watched.
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
core::future::poll_fn(|cx| super::poll_ready(self.source(), cx, interest)).await
}
}
)*};
}
stream_io!(TcpStream);
impl Handle<TcpStream> {
/// Writes all of `buf` as [`write_owned`](Self::write_owned) does, with the kernel's
/// zero-copy send where it has one, and returns the write's result with a [`Released`] that
/// gives `buf` back once the kernel let go of it.
///
/// The write ends once the kernel took the last byte, as `write_owned`'s does, but the kernel
/// keeps reading `buf` until the peer acknowledged every byte; only then does the `Released`
/// resolve to it. So a peer that writes before it reads cannot hold the write up, and writes
/// pipeline: the next one may start while earlier buffers are still out.
///
/// A write of less than the runtime's
/// [`zero_copy_threshold`](crate::runtime::Builder::zero_copy_threshold) (1 MiB by default),
/// where copying costs less, and every write on epoll, kqueue,
/// I/O completion ports or an io_uring kernel without zero-copy sends (or without memory it
/// may lock for them), is copied by the kernel as `write_owned`'s is, and its `Released` is
/// ready at once. So is a write served by a ring only its own thread may reap: a thread's own
/// shard (a stream polled by `block_on` outside the runtime's workers), or the workers of a
/// runtime built with [`handoff_after(None)`](crate::runtime::Builder::handoff_after). Their
/// rings could not be handed to another thread, which a buffer still out when the thread
/// stops would need.
///
/// If the future is dropped before it completes, the stream gets `buf` whole or not at all,
/// as with `write_owned`. Either way `buf` is dropped only once the kernel let go of it. `buf`
/// is any [`IoBuf`](crate::io::IoBuf).
pub async fn write_zero_copy<B>(&self, buf: B) -> (io::Result<usize>, Released<B>)
where
B: IoBuf,
{
self.source().write_zero_copy(buf).await
}
}
#[cfg(unix)]
stream_io!(UnixStream);
#[cfg(unix)]
read_side!(std::io::PipeReader);
#[cfg(unix)]
write_side!(std::io::PipeWriter);