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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use std::io;
use std::pin::Pin;
use std::process::Stdio;
pub type RawPipeHandle = super::RawIoHandle;
// The synchronous read end of a unidirectional pipe.
pub struct PipeRead {
file: std::fs::File,
}
// The asynchronous read end of a unidirectional pipe.
pub struct AsyncPipeRead {
#[cfg(windows)]
/// We use a `ChildStdout` here as it's a much better fit for a Windows named pipe on Windows. We
/// might also be able to use `tokio::net::windows::named_pipe::NamedPipeClient` in the future
/// if those can be created from raw handles down the road.
read: tokio::process::ChildStdout,
#[cfg(not(windows))]
read: tokio::net::unix::pipe::Receiver,
}
// The synchronous write end of a unidirectional pipe.
pub struct PipeWrite {
file: std::fs::File,
}
// The asynchronous write end of a unidirectional pipe.
pub struct AsyncPipeWrite {
#[cfg(windows)]
/// We use a `ChildStdin` here as it's a much better fit for a Windows named pipe on Windows. We
/// might also be able to use `tokio::net::windows::named_pipe::NamedPipeClient` in the future
/// if those can be created from raw handles down the road.
write: tokio::process::ChildStdin,
#[cfg(not(windows))]
write: tokio::net::unix::pipe::Sender,
}
impl PipeRead {
/// Converts this sync reader into an async reader. May fail if the Tokio runtime is
/// unavailable.
#[cfg(windows)]
pub fn into_async(self) -> io::Result<AsyncPipeRead> {
let owned: std::os::windows::io::OwnedHandle = self.file.into();
let stdout = std::process::ChildStdout::from(owned);
Ok(AsyncPipeRead {
read: tokio::process::ChildStdout::from_std(stdout)?,
})
}
/// Converts this sync reader into an async reader. May fail if the Tokio runtime is
/// unavailable.
#[cfg(not(windows))]
pub fn into_async(self) -> io::Result<AsyncPipeRead> {
Ok(AsyncPipeRead {
read: tokio::net::unix::pipe::Receiver::from_file(self.file)?,
})
}
/// Creates a new [`PipeRead`] instance that shares the same underlying file handle
/// as the existing [`PipeRead`] instance.
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self {
file: self.file.try_clone()?,
})
}
}
impl AsyncPipeRead {
/// Converts this async reader into an sync reader. May fail if the Tokio runtime is
/// unavailable.
#[cfg(windows)]
pub fn into_sync(self) -> io::Result<PipeRead> {
let owned = self.read.into_owned_handle()?;
Ok(PipeRead { file: owned.into() })
}
/// Converts this async reader into an sync reader. May fail if the Tokio runtime is
/// unavailable.
#[cfg(not(windows))]
pub fn into_sync(self) -> io::Result<PipeRead> {
let file = self.read.into_nonblocking_fd()?.into();
Ok(PipeRead { file })
}
}
impl std::io::Read for PipeRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.file.read(buf)
}
fn read_vectored(
&mut self,
bufs: &mut [io::IoSliceMut<'_>],
) -> io::Result<usize> {
self.file.read_vectored(bufs)
}
}
impl tokio::io::AsyncRead for AsyncPipeRead {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().read).poll_read(cx, buf)
}
}
impl PipeWrite {
/// Converts this sync writer into an async writer. May fail if the Tokio runtime is
/// unavailable.
#[cfg(windows)]
pub fn into_async(self) -> io::Result<AsyncPipeWrite> {
let owned: std::os::windows::io::OwnedHandle = self.file.into();
let stdin = std::process::ChildStdin::from(owned);
Ok(AsyncPipeWrite {
write: tokio::process::ChildStdin::from_std(stdin)?,
})
}
/// Converts this sync writer into an async writer. May fail if the Tokio runtime is
/// unavailable.
#[cfg(not(windows))]
pub fn into_async(self) -> io::Result<AsyncPipeWrite> {
Ok(AsyncPipeWrite {
write: tokio::net::unix::pipe::Sender::from_file(self.file)?,
})
}
/// Creates a new [`PipeWrite`] instance that shares the same underlying file handle
/// as the existing [`PipeWrite`] instance.
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self {
file: self.file.try_clone()?,
})
}
}
impl AsyncPipeWrite {
/// Converts this async writer into an sync writer. May fail if the Tokio runtime is
/// unavailable.
#[cfg(windows)]
pub fn into_sync(self) -> io::Result<PipeWrite> {
let owned = self.write.into_owned_handle()?;
Ok(PipeWrite { file: owned.into() })
}
/// Converts this async writer into an sync writer. May fail if the Tokio runtime is
/// unavailable.
#[cfg(not(windows))]
pub fn into_sync(self) -> io::Result<PipeWrite> {
let file = self.write.into_nonblocking_fd()?.into();
Ok(PipeWrite { file })
}
}
impl std::io::Write for PipeWrite {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.file.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.file.flush()
}
fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
self.file.write_vectored(bufs)
}
}
impl tokio::io::AsyncWrite for AsyncPipeWrite {
#[inline(always)]
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<Result<usize, io::Error>> {
Pin::new(&mut self.get_mut().write).poll_write(cx, buf)
}
#[inline(always)]
fn poll_flush(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), io::Error>> {
Pin::new(&mut self.get_mut().write).poll_flush(cx)
}
#[inline(always)]
fn poll_shutdown(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), io::Error>> {
Pin::new(&mut self.get_mut().write).poll_shutdown(cx)
}
#[inline(always)]
fn is_write_vectored(&self) -> bool {
self.write.is_write_vectored()
}
#[inline(always)]
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> std::task::Poll<Result<usize, io::Error>> {
Pin::new(&mut self.get_mut().write).poll_write_vectored(cx, bufs)
}
}
impl From<PipeRead> for Stdio {
fn from(val: PipeRead) -> Self {
Stdio::from(val.file)
}
}
impl From<PipeWrite> for Stdio {
fn from(val: PipeWrite) -> Self {
Stdio::from(val.file)
}
}
impl From<PipeRead> for std::fs::File {
fn from(val: PipeRead) -> Self {
val.file
}
}
impl From<PipeWrite> for std::fs::File {
fn from(val: PipeWrite) -> Self {
val.file
}
}
#[cfg(not(windows))]
impl From<PipeRead> for std::os::unix::io::OwnedFd {
fn from(val: PipeRead) -> Self {
val.file.into()
}
}
#[cfg(not(windows))]
impl From<PipeWrite> for std::os::unix::io::OwnedFd {
fn from(val: PipeWrite) -> Self {
val.file.into()
}
}
#[cfg(windows)]
impl From<PipeRead> for std::os::windows::io::OwnedHandle {
fn from(val: PipeRead) -> Self {
val.file.into()
}
}
#[cfg(windows)]
impl From<PipeWrite> for std::os::windows::io::OwnedHandle {
fn from(val: PipeWrite) -> Self {
val.file.into()
}
}
/// Create a unidirectional pipe pair that starts off as a pair of synchronous file handles,
/// but either side may be promoted to an async-capable reader/writer.
///
/// On Windows, we use a named pipe because that's the only way to get reliable async I/O
/// support. On Unix platforms, we use the `os_pipe` library, which uses `pipe2` under the hood
/// (or `pipe` on OSX).
pub fn pipe() -> io::Result<(PipeRead, PipeWrite)> {
pipe_impl()
}
/// Creates a unidirectional pipe on top of a named pipe (which is technically bidirectional).
#[cfg(windows)]
pub fn pipe_impl() -> io::Result<(PipeRead, PipeWrite)> {
// SAFETY: We're careful with handles here
unsafe {
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
let (server, client) = crate::winpipe::create_named_pipe()?;
let read = std::fs::File::from(OwnedHandle::from_raw_handle(client));
let write = std::fs::File::from(OwnedHandle::from_raw_handle(server));
Ok((PipeRead { file: read }, PipeWrite { file: write }))
}
}
/// Creates a unidirectional pipe for unix platforms.
#[cfg(not(windows))]
pub fn pipe_impl() -> io::Result<(PipeRead, PipeWrite)> {
use std::os::unix::io::OwnedFd;
let (read, write) = os_pipe::pipe()?;
let read = std::fs::File::from(Into::<OwnedFd>::into(read));
let write = std::fs::File::from(Into::<OwnedFd>::into(write));
Ok((PipeRead { file: read }, PipeWrite { file: write }))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::io::Write;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
#[test]
fn test_pipe() {
let (mut read, mut write) = pipe().unwrap();
// Write to the server and read from the client
write.write_all(b"hello").unwrap();
let mut buf: [u8; 5] = Default::default();
read.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"hello");
}
#[tokio::test]
async fn test_async_pipe() {
let (read, write) = pipe().unwrap();
let mut read = read.into_async().unwrap();
let mut write = write.into_async().unwrap();
write.write_all(b"hello").await.unwrap();
let mut buf: [u8; 5] = Default::default();
read.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"hello");
}
/// Test a round-trip through async mode and back.
#[tokio::test]
async fn test_pipe_transmute() {
let (mut read, mut write) = pipe().unwrap();
// Sync
write.write_all(b"hello").unwrap();
let mut buf: [u8; 5] = Default::default();
read.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"hello");
let mut read = read.into_async().unwrap();
let mut write = write.into_async().unwrap();
// Async
write.write_all(b"hello").await.unwrap();
let mut buf: [u8; 5] = Default::default();
read.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"hello");
let mut read = read.into_sync().unwrap();
let mut write = write.into_sync().unwrap();
// Sync
write.write_all(b"hello").unwrap();
let mut buf: [u8; 5] = Default::default();
read.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"hello");
}
#[tokio::test]
async fn test_async_pipe_is_nonblocking() {
let (read, write) = pipe().unwrap();
let mut read = read.into_async().unwrap();
let mut write = write.into_async().unwrap();
let a = tokio::spawn(async move {
let mut buf: [u8; 5] = Default::default();
read.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"hello");
});
let b = tokio::spawn(async move {
write.write_all(b"hello").await.unwrap();
});
a.await.unwrap();
b.await.unwrap();
}
}
|