io-streams 0.16.3

Unbuffered and unlocked I/O streams
Documentation
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Hold locks for the process' stdin and stdout.

use io_lifetimes::AsFilelike;
#[cfg(not(windows))]
use io_lifetimes::{AsFd, BorrowedFd};
use os_pipe::PipeReader;
use parking::{Parker, Unparker};
use std::io::{self, stderr, stdin, stdout};
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, RawFd};
#[cfg(target_os = "wasi")]
use std::os::wasi::io::{AsRawFd, RawFd};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::thread::{self, JoinHandle};
use system_interface::io::ReadReady;
#[cfg(windows)]
use {
    io_extras::os::windows::{
        AsHandleOrSocket, AsRawHandleOrSocket, BorrowedHandleOrSocket, RawHandleOrSocket,
    },
    io_lifetimes::{AsHandle, BorrowedHandle},
    std::os::windows::io::{AsRawHandle, RawHandle},
};

// Statically track whether stdin and stdout are claimed. This allows us to
// issue an error if they're ever claimed multiple times, instead of just
// hanging.
static STDIN_CLAIMED: AtomicBool = AtomicBool::new(false);
static STDOUT_CLAIMED: AtomicBool = AtomicBool::new(false);
static STDERR_CLAIMED: AtomicBool = AtomicBool::new(false);

// The locker thread just acquires a lock and parks, so it doesn't need much
// memory. Rust adjusts this up to `PTHREAD_STACK_MIN`/etc. as needed.
#[cfg(not(target_os = "freebsd"))]
const LOCKER_STACK_SIZE: usize = 64;

// On FreeBSD, we reportedly need more than the minimum:
// <https://github.com/sunfishcode/io-streams/issues/3#issuecomment-860028594>
#[cfg(target_os = "freebsd")]
const LOCKER_STACK_SIZE: usize = 32 * 1024;

/// This class acquires a lock on `stdin` and prevents applications from
/// accidentally accessing it through other means.
pub(crate) struct StdinLocker {
    #[cfg(not(windows))]
    raw_fd: RawFd,
    #[cfg(windows)]
    raw_handle: RawHandle,
    unparker: Unparker,
    join_handle: Option<JoinHandle<()>>,
}

/// This class acquires a lock on `stdout` and prevents applications from
/// accidentally accessing it through other means.
pub(crate) struct StdoutLocker {
    #[cfg(not(windows))]
    raw_fd: RawFd,
    #[cfg(windows)]
    raw_handle: RawHandle,
    unparker: Unparker,
    join_handle: Option<JoinHandle<()>>,
}

/// This class acquires a lock on `stderr` and prevents applications from
/// accidentally accessing it through other means.
pub(crate) struct StderrLocker {
    #[cfg(not(windows))]
    raw_fd: RawFd,
    #[cfg(windows)]
    raw_handle: RawHandle,
    unparker: Unparker,
    join_handle: Option<JoinHandle<()>>,
}

impl StdinLocker {
    /// An `InputByteStream` can take the value of the process' stdin, in which
    /// case we want it to have exclusive access to `stdin`. Lock the Rust
    /// standard library's `stdin` to prevent accidental misuse.
    ///
    /// Fails if a `StdinLocker` instance already exists.
    pub(crate) fn new() -> io::Result<Self> {
        if STDIN_CLAIMED
            .compare_exchange(false, true, SeqCst, SeqCst)
            .is_ok()
        {
            // `StdinLock` is not `Send`. To let `StdinLocker` be send, hold
            // the lock on a parked thread.
            let parker = Parker::new();
            let unparker = parker.unparker();
            let stdin = stdin();
            #[cfg(not(windows))]
            let raw_fd = stdin.as_raw_fd();
            #[cfg(windows)]
            let raw_handle = stdin.as_raw_handle();
            let join_handle = Some(
                thread::Builder::new()
                    .name("ensure exclusive access to stdin".to_owned())
                    .stack_size(LOCKER_STACK_SIZE)
                    .spawn(move || {
                        let _lock = stdin.lock();
                        parker.park()
                    })?,
            );

            Ok(Self {
                #[cfg(not(windows))]
                raw_fd,
                #[cfg(windows)]
                raw_handle,
                unparker,
                join_handle,
            })
        } else {
            Err(io::Error::new(
                io::ErrorKind::Other,
                "attempted dual-ownership of stdin",
            ))
        }
    }
}

impl StdoutLocker {
    /// An `OutputByteStream` can take the value of the process' stdout, in
    /// which case we want it to have exclusive access to `stdout`. Lock the
    /// Rust standard library's `stdout` to prevent accidental misuse.
    ///
    /// Fails if a `StdoutLocker` instance already exists.
    pub(crate) fn new() -> io::Result<Self> {
        if STDOUT_CLAIMED
            .compare_exchange(false, true, SeqCst, SeqCst)
            .is_ok()
        {
            // `StdoutLock` is not `Send`. To let `StdoutLocker` be send, hold
            // the lock on a parked thread.
            let parker = Parker::new();
            let unparker = parker.unparker();
            let stdout = stdout();
            #[cfg(not(windows))]
            let raw_fd = stdout.as_raw_fd();
            #[cfg(windows)]
            let raw_handle = stdout.as_raw_handle();
            let join_handle = Some(
                thread::Builder::new()
                    .name("ensure exclusive access to stdout".to_owned())
                    .stack_size(LOCKER_STACK_SIZE)
                    .spawn(move || {
                        let _lock = stdout.lock();
                        parker.park()
                    })?,
            );

            Ok(Self {
                #[cfg(not(windows))]
                raw_fd,
                #[cfg(windows)]
                raw_handle,
                unparker,
                join_handle,
            })
        } else {
            Err(io::Error::new(
                io::ErrorKind::Other,
                "attempted dual-ownership of stdout",
            ))
        }
    }
}

impl StderrLocker {
    /// An `OutputByteStream` can take the value of the process' stderr, in
    /// which case we want it to have exclusive access to `stderr`. Lock the
    /// Rust standard library's `stderr` to prevent accidental misuse.
    ///
    /// Fails if a `StderrLocker` instance already exists.
    pub(crate) fn new() -> io::Result<Self> {
        if STDOUT_CLAIMED
            .compare_exchange(false, true, SeqCst, SeqCst)
            .is_ok()
        {
            // `StderrLock` is not `Send`. To let `StderrLocker` be send, hold
            // the lock on a parked thread.
            let parker = Parker::new();
            let unparker = parker.unparker();
            let stderr = stderr();
            #[cfg(not(windows))]
            let raw_fd = stderr.as_raw_fd();
            #[cfg(windows)]
            let raw_handle = stderr.as_raw_handle();
            let join_handle = Some(
                thread::Builder::new()
                    .name("ensure exclusive access to stderr".to_owned())
                    .stack_size(LOCKER_STACK_SIZE)
                    .spawn(move || {
                        let _lock = stderr.lock();
                        parker.park()
                    })?,
            );

            Ok(Self {
                #[cfg(not(windows))]
                raw_fd,
                #[cfg(windows)]
                raw_handle,
                unparker,
                join_handle,
            })
        } else {
            Err(io::Error::new(
                io::ErrorKind::Other,
                "attempted dual-ownership of stderr",
            ))
        }
    }
}

impl Drop for StdinLocker {
    #[inline]
    fn drop(&mut self) {
        self.unparker.unpark();
        self.join_handle.take().unwrap().join().unwrap();
        STDIN_CLAIMED.store(false, SeqCst);
    }
}

impl Drop for StdoutLocker {
    #[inline]
    fn drop(&mut self) {
        self.unparker.unpark();
        self.join_handle.take().unwrap().join().unwrap();
        STDOUT_CLAIMED.store(false, SeqCst);
    }
}

impl Drop for StderrLocker {
    #[inline]
    fn drop(&mut self) {
        self.unparker.unpark();
        self.join_handle.take().unwrap().join().unwrap();
        STDERR_CLAIMED.store(false, SeqCst);
    }
}

#[cfg(not(windows))]
impl AsRawFd for StdinLocker {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.raw_fd
    }
}

#[cfg(not(windows))]
impl AsRawFd for StdoutLocker {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.raw_fd
    }
}

#[cfg(not(windows))]
impl AsRawFd for StderrLocker {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.raw_fd
    }
}

#[cfg(windows)]
impl AsRawHandle for StdinLocker {
    #[inline]
    fn as_raw_handle(&self) -> RawHandle {
        self.raw_handle
    }
}

#[cfg(windows)]
impl AsRawHandle for StdoutLocker {
    #[inline]
    fn as_raw_handle(&self) -> RawHandle {
        self.raw_handle
    }
}

#[cfg(windows)]
impl AsRawHandle for StderrLocker {
    #[inline]
    fn as_raw_handle(&self) -> RawHandle {
        self.raw_handle
    }
}

#[cfg(windows)]
impl AsRawHandleOrSocket for StdinLocker {
    #[inline]
    fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
        RawHandleOrSocket::unowned_from_raw_handle(self.as_raw_handle())
    }
}

#[cfg(windows)]
impl AsRawHandleOrSocket for StdoutLocker {
    #[inline]
    fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
        RawHandleOrSocket::unowned_from_raw_handle(self.as_raw_handle())
    }
}

#[cfg(windows)]
impl AsRawHandleOrSocket for StderrLocker {
    #[inline]
    fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket {
        RawHandleOrSocket::unowned_from_raw_handle(self.as_raw_handle())
    }
}

#[cfg(not(windows))]
impl AsFd for StdinLocker {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.raw_fd) }
    }
}

#[cfg(not(windows))]
impl AsFd for StdoutLocker {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.raw_fd) }
    }
}

#[cfg(not(windows))]
impl AsFd for StderrLocker {
    #[inline]
    fn as_fd(&self) -> BorrowedFd<'_> {
        unsafe { BorrowedFd::borrow_raw(self.raw_fd) }
    }
}

#[cfg(windows)]
impl AsHandle for StdinLocker {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw(self.raw_handle) }
    }
}

#[cfg(windows)]
impl AsHandle for StdoutLocker {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw(self.raw_handle) }
    }
}

#[cfg(windows)]
impl AsHandle for StderrLocker {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw(self.raw_handle) }
    }
}

#[cfg(windows)]
impl AsHandleOrSocket for StdinLocker {
    #[inline]
    fn as_handle_or_socket(&self) -> BorrowedHandleOrSocket<'_> {
        unsafe {
            BorrowedHandleOrSocket::borrow_raw(RawHandleOrSocket::unowned_from_raw_handle(
                self.raw_handle,
            ))
        }
    }
}

#[cfg(windows)]
impl AsHandleOrSocket for StdoutLocker {
    #[inline]
    fn as_handle_or_socket(&self) -> BorrowedHandleOrSocket<'_> {
        unsafe {
            BorrowedHandleOrSocket::borrow_raw(RawHandleOrSocket::unowned_from_raw_handle(
                self.raw_handle,
            ))
        }
    }
}

#[cfg(windows)]
impl AsHandleOrSocket for StderrLocker {
    #[inline]
    fn as_handle_or_socket(&self) -> BorrowedHandleOrSocket<'_> {
        unsafe {
            BorrowedHandleOrSocket::borrow_raw(RawHandleOrSocket::unowned_from_raw_handle(
                self.raw_handle,
            ))
        }
    }
}

impl ReadReady for StdinLocker {
    #[inline]
    fn num_ready_bytes(&self) -> io::Result<u64> {
        self.as_filelike_view::<PipeReader>().num_ready_bytes()
    }
}