stdio.rs 36.8 KB
Newer Older
1 2
#![cfg_attr(test, allow(unused))]

3 4 5
#[cfg(test)]
mod tests;

T
Taiki Endo 已提交
6
use crate::io::prelude::*;
7

8
use crate::cell::{Cell, RefCell};
T
Taiki Endo 已提交
9
use crate::fmt;
M
Mark Rousskov 已提交
10
use crate::io::{self, BufReader, Initializer, IoSlice, IoSliceMut, LineWriter};
11
use crate::lazy::SyncOnceCell;
12
use crate::pin::Pin;
13
use crate::sync::atomic::{AtomicBool, Ordering};
14
use crate::sync::{Arc, Mutex, MutexGuard};
T
Taiki Endo 已提交
15 16
use crate::sys::stdio;
use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
17

18
type LocalStream = Arc<Mutex<Vec<u8>>>;
19

20
thread_local! {
21 22
    /// Used by the test crate to capture the output of the print macros and panics.
    static OUTPUT_CAPTURE: Cell<Option<LocalStream>> = {
23
        Cell::new(None)
24 25 26
    }
}

27
/// Flag to indicate OUTPUT_CAPTURE is used.
28
///
29 30 31
/// If it is None and was never set on any thread, this flag is set to false,
/// and OUTPUT_CAPTURE can be safely ignored on all threads, saving some time
/// and memory registering an unused thread local.
32
///
33 34
/// Note about memory ordering: This contains information about whether a
/// thread local variable might be in use. Although this is a global flag, the
35
/// memory ordering between threads does not matter: we only want this flag to
36
/// have a consistent order between set_output_capture and print_to *within
37 38
/// the same thread*. Within the same thread, things always have a perfectly
/// consistent order. So Ordering::Relaxed is fine.
39
static OUTPUT_CAPTURE_USED: AtomicBool = AtomicBool::new(false);
40

41 42 43
/// A handle to a raw instance of the standard input stream of this process.
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
44 45
/// the `std::io::stdio::stdin_raw` function.
struct StdinRaw(stdio::Stdin);
46 47 48 49

/// A handle to a raw instance of the standard output stream of this process.
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
50 51
/// the `std::io::stdio::stdout_raw` function.
struct StdoutRaw(stdio::Stdout);
52 53 54 55

/// A handle to a raw instance of the standard output stream of this process.
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
56 57
/// the `std::io::stdio::stderr_raw` function.
struct StderrRaw(stdio::Stderr);
58

59
/// Constructs a new raw handle to the standard input of this process.
60 61 62 63 64 65
///
/// The returned handle does not interact with any other handles created nor
/// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
/// handles is **not** available to raw handles returned from this function.
///
/// The returned handle has no external synchronization or buffering.
66 67
#[unstable(feature = "libstd_sys_internals", issue = "none")]
const fn stdin_raw() -> StdinRaw {
68
    StdinRaw(stdio::Stdin::new())
M
Mark Rousskov 已提交
69
}
70

71
/// Constructs a new raw handle to the standard output stream of this process.
72 73 74
///
/// The returned handle does not interact with any other handles created nor
/// handles returned by `std::io::stdout`. Note that data is buffered by the
75
/// `std::io::stdout` handles so writes which happen via this raw handle may
76 77 78 79
/// appear before previous writes.
///
/// The returned handle has no external synchronization or buffering layered on
/// top.
80 81
#[unstable(feature = "libstd_sys_internals", issue = "none")]
const fn stdout_raw() -> StdoutRaw {
82
    StdoutRaw(stdio::Stdout::new())
M
Mark Rousskov 已提交
83
}
84

85
/// Constructs a new raw handle to the standard error stream of this process.
86 87
///
/// The returned handle does not interact with any other handles created nor
88
/// handles returned by `std::io::stderr`.
89 90 91
///
/// The returned handle has no external synchronization or buffering layered on
/// top.
92 93
#[unstable(feature = "libstd_sys_internals", issue = "none")]
const fn stderr_raw() -> StderrRaw {
94
    StderrRaw(stdio::Stderr::new())
M
Mark Rousskov 已提交
95
}
96 97

impl Read for StdinRaw {
M
Mark Rousskov 已提交
98
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
99
        handle_ebadf(self.0.read(buf), 0)
M
Mark Rousskov 已提交
100
    }
S
Steven Fackler 已提交
101

S
Steven Fackler 已提交
102
    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
103
        handle_ebadf(self.0.read_vectored(bufs), 0)
104 105
    }

106
    #[inline]
S
Steven Fackler 已提交
107 108
    fn is_read_vectored(&self) -> bool {
        self.0.is_read_vectored()
109 110
    }

S
Steven Fackler 已提交
111 112 113
    #[inline]
    unsafe fn initializer(&self) -> Initializer {
        Initializer::nop()
114
    }
115 116

    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
117
        handle_ebadf(self.0.read_to_end(buf), 0)
118 119 120
    }

    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
121
        handle_ebadf(self.0.read_to_string(buf), 0)
122
    }
123
}
124

125
impl Write for StdoutRaw {
M
Mark Rousskov 已提交
126
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
127
        handle_ebadf(self.0.write(buf), buf.len())
M
Mark Rousskov 已提交
128
    }
129

S
Steven Fackler 已提交
130
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
131 132
        let total = bufs.iter().map(|b| b.len()).sum();
        handle_ebadf(self.0.write_vectored(bufs), total)
133 134
    }

135
    #[inline]
S
Steven Fackler 已提交
136 137
    fn is_write_vectored(&self) -> bool {
        self.0.is_write_vectored()
138 139
    }

M
Mark Rousskov 已提交
140
    fn flush(&mut self) -> io::Result<()> {
141
        handle_ebadf(self.0.flush(), ())
M
Mark Rousskov 已提交
142
    }
143 144

    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
145
        handle_ebadf(self.0.write_all(buf), ())
146 147 148
    }

    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
149
        handle_ebadf(self.0.write_all_vectored(bufs), ())
150 151 152
    }

    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
153
        handle_ebadf(self.0.write_fmt(fmt), ())
154
    }
155
}
156

157
impl Write for StderrRaw {
M
Mark Rousskov 已提交
158
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
159
        handle_ebadf(self.0.write(buf), buf.len())
M
Mark Rousskov 已提交
160
    }
161

S
Steven Fackler 已提交
162
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
163 164
        let total = bufs.iter().map(|b| b.len()).sum();
        handle_ebadf(self.0.write_vectored(bufs), total)
165 166
    }

167
    #[inline]
S
Steven Fackler 已提交
168 169
    fn is_write_vectored(&self) -> bool {
        self.0.is_write_vectored()
170 171
    }

M
Mark Rousskov 已提交
172
    fn flush(&mut self) -> io::Result<()> {
173
        handle_ebadf(self.0.flush(), ())
M
Mark Rousskov 已提交
174
    }
175 176

    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
177
        handle_ebadf(self.0.write_all(buf), ())
178 179 180
    }

    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
181
        handle_ebadf(self.0.write_all_vectored(bufs), ())
182 183 184
    }

    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
185
        handle_ebadf(self.0.write_fmt(fmt), ())
186
    }
S
Steven Fackler 已提交
187 188 189 190
}

fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
    match r {
191
        Err(ref e) if stdio::is_ebadf(e) => Ok(default),
M
Mark Rousskov 已提交
192
        r => r,
S
Steven Fackler 已提交
193 194 195
    }
}

196 197 198
/// A handle to the standard input stream of a process.
///
/// Each handle is a shared reference to a global buffer of input data to this
T
Tshepang Lekhonkhobe 已提交
199
/// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
200
/// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
201
/// to other reads.
202 203 204
///
/// This handle implements the `Read` trait, but beware that concurrent reads
/// of `Stdin` must be executed with care.
205
///
T
Tshepang Lekhonkhobe 已提交
206
/// Created by the [`io::stdin`] method.
207
///
208
/// [`io::stdin`]: stdin
209 210
///
/// ### Note: Windows Portability Consideration
211
///
212 213 214
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
/// an error.
215 216 217 218 219 220 221 222 223 224 225 226 227
///
/// # Examples
///
/// ```no_run
/// use std::io::{self, Read};
///
/// fn main() -> io::Result<()> {
///     let mut buffer = String::new();
///     let mut stdin = io::stdin(); // We get `Stdin` here.
///     stdin.read_to_string(&mut buffer)?;
///     Ok(())
/// }
/// ```
A
Alex Crichton 已提交
228
#[stable(feature = "rust1", since = "1.0.0")]
229
pub struct Stdin {
230
    inner: &'static Mutex<BufReader<StdinRaw>>,
231 232
}

I
Ivan Tham 已提交
233
/// A locked reference to the [`Stdin`] handle.
234
///
T
Tshepang Lekhonkhobe 已提交
235 236
/// This handle implements both the [`Read`] and [`BufRead`] traits, and
/// is constructed via the [`Stdin::lock`] method.
237
///
238
/// ### Note: Windows Portability Consideration
239
///
240 241 242
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
/// an error.
243 244 245 246 247 248 249 250 251 252
///
/// # Examples
///
/// ```no_run
/// use std::io::{self, Read};
///
/// fn main() -> io::Result<()> {
///     let mut buffer = String::new();
///     let stdin = io::stdin(); // We get `Stdin` here.
///     {
253 254
///         let mut handle = stdin.lock(); // We get `StdinLock` here.
///         handle.read_to_string(&mut buffer)?;
255 256 257 258
///     } // `StdinLock` is dropped here.
///     Ok(())
/// }
/// ```
A
Alex Crichton 已提交
259
#[stable(feature = "rust1", since = "1.0.0")]
260
pub struct StdinLock<'a> {
261
    inner: MutexGuard<'a, BufReader<StdinRaw>>,
262 263
}

S
Steve Klabnik 已提交
264
/// Constructs a new handle to the standard input of the current process.
265
///
S
Steve Klabnik 已提交
266 267
/// Each handle returned is a reference to a shared global buffer whose access
/// is synchronized via a mutex. If you need more explicit control over
268
/// locking, see the [`Stdin::lock`] method.
S
Steve Klabnik 已提交
269
///
270 271 272 273 274
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
/// an error.
///
S
Steve Klabnik 已提交
275 276 277 278
/// # Examples
///
/// Using implicit synchronization:
///
279
/// ```no_run
S
Steve Klabnik 已提交
280 281
/// use std::io::{self, Read};
///
282 283 284 285 286
/// fn main() -> io::Result<()> {
///     let mut buffer = String::new();
///     io::stdin().read_to_string(&mut buffer)?;
///     Ok(())
/// }
S
Steve Klabnik 已提交
287 288 289
/// ```
///
/// Using explicit synchronization:
290
///
291
/// ```no_run
S
Steve Klabnik 已提交
292 293
/// use std::io::{self, Read};
///
294 295 296 297
/// fn main() -> io::Result<()> {
///     let mut buffer = String::new();
///     let stdin = io::stdin();
///     let mut handle = stdin.lock();
S
Steve Klabnik 已提交
298
///
299 300 301
///     handle.read_to_string(&mut buffer)?;
///     Ok(())
/// }
S
Steve Klabnik 已提交
302
/// ```
A
Alex Crichton 已提交
303
#[stable(feature = "rust1", since = "1.0.0")]
304
pub fn stdin() -> Stdin {
305
    static INSTANCE: SyncOnceCell<Mutex<BufReader<StdinRaw>>> = SyncOnceCell::new();
306
    Stdin {
307 308 309
        inner: INSTANCE.get_or_init(|| {
            Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin_raw()))
        }),
310 311 312
    }
}

T
Taylor Yu 已提交
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
/// Constructs a new locked handle to the standard input of the current
/// process.
///
/// Each handle returned is a guard granting locked access to a shared
/// global buffer whose access is synchronized via a mutex. If you need
/// more explicit control over locking, for example, in a multi-threaded
/// program, use the [`io::stdin`] function to obtain an unlocked handle,
/// along with the [`Stdin::lock`] method.
///
/// The lock is released when the returned guard goes out of scope. The
/// returned guard also implements the [`Read`] and [`BufRead`] traits for
/// accessing the underlying data.
///
/// **Note**: The mutex locked by this handle is not reentrant. Even in a
/// single-threaded program, calling other code that accesses [`Stdin`]
/// could cause a deadlock or panic, if this locked handle is held across
/// that call.
///
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
/// an error.
///
/// # Examples
///
/// ```no_run
/// #![feature(stdio_locked)]
/// use std::io::{self, Read};
///
/// fn main() -> io::Result<()> {
///     let mut buffer = String::new();
///     let mut handle = io::stdin_locked();
///
///     handle.read_to_string(&mut buffer)?;
///     Ok(())
/// }
/// ```
T
Taylor Yu 已提交
350
#[unstable(feature = "stdio_locked", issue = "86845")]
351 352
pub fn stdin_locked() -> StdinLock<'static> {
    stdin().into_locked()
T
Taylor Yu 已提交
353 354
}

355
impl Stdin {
356
    /// Locks this handle to the standard input stream, returning a readable
357 358 359
    /// guard.
    ///
    /// The lock is released when the returned lock goes out of scope. The
T
Tshepang Lekhonkhobe 已提交
360
    /// returned guard also implements the [`Read`] and [`BufRead`] traits for
361
    /// accessing the underlying data.
362
    ///
G
Guillaume Gomez 已提交
363 364
    /// # Examples
    ///
365
    /// ```no_run
G
Guillaume Gomez 已提交
366 367
    /// use std::io::{self, Read};
    ///
368 369 370 371
    /// fn main() -> io::Result<()> {
    ///     let mut buffer = String::new();
    ///     let stdin = io::stdin();
    ///     let mut handle = stdin.lock();
G
Guillaume Gomez 已提交
372
    ///
373 374 375
    ///     handle.read_to_string(&mut buffer)?;
    ///     Ok(())
    /// }
G
Guillaume Gomez 已提交
376
    /// ```
A
Alex Crichton 已提交
377
    #[stable(feature = "rust1", since = "1.0.0")]
378
    pub fn lock(&self) -> StdinLock<'_> {
T
Taylor Yu 已提交
379
        self.lock_any()
380
    }
A
Alex Crichton 已提交
381

382
    /// Locks this handle and reads a line of input, appending it to the specified buffer.
A
Alex Crichton 已提交
383 384
    ///
    /// For detailed semantics of this method, see the documentation on
T
Tshepang Lekhonkhobe 已提交
385
    /// [`BufRead::read_line`].
386
    ///
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    /// # Examples
    ///
    /// ```no_run
    /// use std::io;
    ///
    /// let mut input = String::new();
    /// match io::stdin().read_line(&mut input) {
    ///     Ok(n) => {
    ///         println!("{} bytes read", n);
    ///         println!("{}", input);
    ///     }
    ///     Err(error) => println!("error: {}", error),
    /// }
    /// ```
    ///
    /// You can run the example one of two ways:
    ///
404
    /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
405
    /// - Give it text interactively by running the executable directly,
T
Tshepang Lekhonkhobe 已提交
406
    ///   in which case it will wait for the Enter key to be pressed before
407
    ///   continuing
A
Alex Crichton 已提交
408
    #[stable(feature = "rust1", since = "1.0.0")]
409
    pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
A
Alex Crichton 已提交
410 411
        self.lock().read_line(buf)
    }
T
Taylor Yu 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

    // Locks this handle with any lifetime. This depends on the
    // implementation detail that the underlying `Mutex` is static.
    fn lock_any<'a>(&self) -> StdinLock<'a> {
        StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
    }

    /// Consumes this handle to the standard input stream, locking the
    /// shared global buffer associated with the stream and returning a
    /// readable guard.
    ///
    /// The lock is released when the returned guard goes out of scope. The
    /// returned guard also implements the [`Read`] and [`BufRead`] traits
    /// for accessing the underlying data.
    ///
    /// It is often simpler to directly get a locked handle using the
    /// [`stdin_locked`] function instead, unless nearby code also needs to
    /// use an unlocked handle.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// #![feature(stdio_locked)]
    /// use std::io::{self, Read};
    ///
    /// fn main() -> io::Result<()> {
    ///     let mut buffer = String::new();
439
    ///     let mut handle = io::stdin().into_locked();
T
Taylor Yu 已提交
440 441 442 443 444
    ///
    ///     handle.read_to_string(&mut buffer)?;
    ///     Ok(())
    /// }
    /// ```
T
Taylor Yu 已提交
445
    #[unstable(feature = "stdio_locked", issue = "86845")]
446
    pub fn into_locked(self) -> StdinLock<'static> {
T
Taylor Yu 已提交
447 448
        self.lock_any()
    }
449 450
}

451
#[stable(feature = "std_debug", since = "1.16.0")]
452
impl fmt::Debug for Stdin {
453
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454
        f.debug_struct("Stdin").finish_non_exhaustive()
455 456 457
    }
}

A
Alex Crichton 已提交
458
#[stable(feature = "rust1", since = "1.0.0")]
459 460 461 462
impl Read for Stdin {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.lock().read(buf)
    }
S
Steven Fackler 已提交
463
    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
464 465
        self.lock().read_vectored(bufs)
    }
S
Steven Fackler 已提交
466
    #[inline]
S
Steven Fackler 已提交
467 468
    fn is_read_vectored(&self) -> bool {
        self.lock().is_read_vectored()
469 470
    }
    #[inline]
S
Steven Fackler 已提交
471 472 473
    unsafe fn initializer(&self) -> Initializer {
        Initializer::nop()
    }
A
Alex Crichton 已提交
474
    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
475 476
        self.lock().read_to_end(buf)
    }
A
Alex Crichton 已提交
477
    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
478 479
        self.lock().read_to_string(buf)
    }
480 481 482
    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        self.lock().read_exact(buf)
    }
483 484
}

T
The8472 已提交
485 486
// only used by platform-dependent io::copy specializations, i.e. unused on some platforms
#[cfg(any(target_os = "linux", target_os = "android"))]
487 488 489 490 491 492
impl StdinLock<'_> {
    pub(crate) fn as_mut_buf(&mut self) -> &mut BufReader<impl Read> {
        &mut self.inner
    }
}

A
Alex Crichton 已提交
493
#[stable(feature = "rust1", since = "1.0.0")]
494
impl Read for StdinLock<'_> {
495 496 497
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }
498

S
Steven Fackler 已提交
499
    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
500 501 502
        self.inner.read_vectored(bufs)
    }

503
    #[inline]
S
Steven Fackler 已提交
504 505
    fn is_read_vectored(&self) -> bool {
        self.inner.is_read_vectored()
506 507
    }

S
Steven Fackler 已提交
508 509 510
    #[inline]
    unsafe fn initializer(&self) -> Initializer {
        Initializer::nop()
511
    }
512 513 514 515 516 517 518 519 520 521 522 523

    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
        self.inner.read_to_end(buf)
    }

    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
        self.inner.read_to_string(buf)
    }

    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        self.inner.read_exact(buf)
    }
524
}
S
Steven Fackler 已提交
525

A
Alex Crichton 已提交
526
#[stable(feature = "rust1", since = "1.0.0")]
527
impl BufRead for StdinLock<'_> {
M
Mark Rousskov 已提交
528 529 530
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        self.inner.fill_buf()
    }
531

M
Mark Rousskov 已提交
532 533 534
    fn consume(&mut self, n: usize) {
        self.inner.consume(n)
    }
535 536 537 538 539 540 541 542

    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
        self.inner.read_until(byte, buf)
    }

    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
        self.inner.read_line(buf)
    }
543 544
}

545
#[stable(feature = "std_debug", since = "1.16.0")]
546
impl fmt::Debug for StdinLock<'_> {
547
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548
        f.debug_struct("StdinLock").finish_non_exhaustive()
549 550 551
    }
}

552 553 554 555
/// A handle to the global standard output stream of the current process.
///
/// Each handle shares a global buffer of data to be written to the standard
/// output stream. Access is also synchronized via a lock and explicit control
556
/// over locking is available via the [`lock`] method.
557
///
T
Tshepang Lekhonkhobe 已提交
558
/// Created by the [`io::stdout`] method.
559
///
560 561 562 563 564
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
///
565 566
/// [`lock`]: Stdout::lock
/// [`io::stdout`]: stdout
A
Alex Crichton 已提交
567
#[stable(feature = "rust1", since = "1.0.0")]
568 569 570 571
pub struct Stdout {
    // FIXME: this should be LineWriter or BufWriter depending on the state of
    //        stdout (tty or not). Note that if this is not line buffered it
    //        should also flush-on-panic or some form of flush-on-abort.
572
    inner: Pin<&'static ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>>,
573 574
}

I
Ivan Tham 已提交
575
/// A locked reference to the [`Stdout`] handle.
576
///
T
Tshepang Lekhonkhobe 已提交
577
/// This handle implements the [`Write`] trait, and is constructed via
578
/// the [`Stdout::lock`] method. See its documentation for more.
579
///
580 581 582 583
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
A
Alex Crichton 已提交
584
#[stable(feature = "rust1", since = "1.0.0")]
585
pub struct StdoutLock<'a> {
586
    inner: ReentrantMutexGuard<'a, RefCell<LineWriter<StdoutRaw>>>,
587 588
}

C
Christiaan Dirkx 已提交
589 590
static STDOUT: SyncOnceCell<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> = SyncOnceCell::new();

S
Steve Klabnik 已提交
591
/// Constructs a new handle to the standard output of the current process.
592 593
///
/// Each handle returned is a reference to a shared global buffer whose access
S
Steve Klabnik 已提交
594
/// is synchronized via a mutex. If you need more explicit control over
595
/// locking, see the [`Stdout::lock`] method.
S
Steve Klabnik 已提交
596
///
597 598 599 600 601
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
///
S
Steve Klabnik 已提交
602 603 604 605
/// # Examples
///
/// Using implicit synchronization:
///
606
/// ```no_run
S
Steve Klabnik 已提交
607 608
/// use std::io::{self, Write};
///
609
/// fn main() -> io::Result<()> {
610
///     io::stdout().write_all(b"hello world")?;
611
///
612 613
///     Ok(())
/// }
S
Steve Klabnik 已提交
614 615 616 617
/// ```
///
/// Using explicit synchronization:
///
618
/// ```no_run
S
Steve Klabnik 已提交
619 620
/// use std::io::{self, Write};
///
621 622 623
/// fn main() -> io::Result<()> {
///     let stdout = io::stdout();
///     let mut handle = stdout.lock();
S
Steve Klabnik 已提交
624
///
625
///     handle.write_all(b"hello world")?;
S
Steve Klabnik 已提交
626
///
627 628
///     Ok(())
/// }
S
Steve Klabnik 已提交
629
/// ```
A
Alex Crichton 已提交
630
#[stable(feature = "rust1", since = "1.0.0")]
631
pub fn stdout() -> Stdout {
632
    Stdout {
C
Christiaan Dirkx 已提交
633 634
        inner: Pin::static_ref(&STDOUT).get_or_init_pin(
            || unsafe { ReentrantMutex::new(RefCell::new(LineWriter::new(stdout_raw()))) },
635 636
            |mutex| unsafe { mutex.init() },
        ),
637 638 639
    }
}

T
Taylor Yu 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
/// Constructs a new locked handle to the standard output of the current
/// process.
///
/// Each handle returned is a guard granting locked access to a shared
/// global buffer whose access is synchronized via a mutex. If you need
/// more explicit control over locking, for example, in a multi-threaded
/// program, use the [`io::stdout`] function to obtain an unlocked handle,
/// along with the [`Stdout::lock`] method.
///
/// The lock is released when the returned guard goes out of scope. The
/// returned guard also implements the [`Write`] trait for writing data.
///
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
///
/// # Examples
///
/// ```no_run
/// #![feature(stdio_locked)]
/// use std::io::{self, Write};
///
/// fn main() -> io::Result<()> {
///     let mut handle = io::stdout_locked();
///
///     handle.write_all(b"hello world")?;
///
///     Ok(())
/// }
/// ```
T
Taylor Yu 已提交
671
#[unstable(feature = "stdio_locked", issue = "86845")]
T
Taylor Yu 已提交
672
pub fn stdout_locked() -> StdoutLock<'static> {
673
    stdout().into_locked()
T
Taylor Yu 已提交
674 675
}

C
Christiaan Dirkx 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689
pub fn cleanup() {
    if let Some(instance) = STDOUT.get() {
        // Flush the data and disable buffering during shutdown
        // by replacing the line writer by one with zero
        // buffering capacity.
        // We use try_lock() instead of lock(), because someone
        // might have leaked a StdoutLock, which would
        // otherwise cause a deadlock here.
        if let Some(lock) = Pin::static_ref(instance).try_lock() {
            *lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
        }
    }
}

690
impl Stdout {
691
    /// Locks this handle to the standard output stream, returning a writable
692 693 694 695
    /// guard.
    ///
    /// The lock is released when the returned lock goes out of scope. The
    /// returned guard also implements the `Write` trait for writing data.
G
Guillaume Gomez 已提交
696 697 698
    ///
    /// # Examples
    ///
699
    /// ```no_run
G
Guillaume Gomez 已提交
700 701
    /// use std::io::{self, Write};
    ///
702 703 704
    /// fn main() -> io::Result<()> {
    ///     let stdout = io::stdout();
    ///     let mut handle = stdout.lock();
G
Guillaume Gomez 已提交
705
    ///
706
    ///     handle.write_all(b"hello world")?;
G
Guillaume Gomez 已提交
707
    ///
708 709
    ///     Ok(())
    /// }
G
Guillaume Gomez 已提交
710
    /// ```
A
Alex Crichton 已提交
711
    #[stable(feature = "rust1", since = "1.0.0")]
712
    pub fn lock(&self) -> StdoutLock<'_> {
T
Taylor Yu 已提交
713 714 715 716 717 718 719
        self.lock_any()
    }

    // Locks this handle with any lifetime. This depends on the
    // implementation detail that the underlying `ReentrantMutex` is
    // static.
    fn lock_any<'a>(&self) -> StdoutLock<'a> {
720
        StdoutLock { inner: self.inner.lock() }
721
    }
T
Taylor Yu 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

    /// Consumes this handle to the standard output stream, locking the
    /// shared global buffer associated with the stream and returning a
    /// writable guard.
    ///
    /// The lock is released when the returned lock goes out of scope. The
    /// returned guard also implements the [`Write`] trait for writing data.
    ///
    /// It is often simpler to directly get a locked handle using the
    /// [`io::stdout_locked`] function instead, unless nearby code also
    /// needs to use an unlocked handle.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// #![feature(stdio_locked)]
    /// use std::io::{self, Write};
    ///
    /// fn main() -> io::Result<()> {
741
    ///     let mut handle = io::stdout().into_locked();
T
Taylor Yu 已提交
742 743 744 745 746 747
    ///
    ///     handle.write_all(b"hello world")?;
    ///
    ///     Ok(())
    /// }
    /// ```
T
Taylor Yu 已提交
748
    #[unstable(feature = "stdio_locked", issue = "86845")]
749
    pub fn into_locked(self) -> StdoutLock<'static> {
T
Taylor Yu 已提交
750 751
        self.lock_any()
    }
752 753
}

754
#[stable(feature = "std_debug", since = "1.16.0")]
755
impl fmt::Debug for Stdout {
756
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757
        f.debug_struct("Stdout").finish_non_exhaustive()
758 759 760
    }
}

A
Alex Crichton 已提交
761
#[stable(feature = "rust1", since = "1.0.0")]
762 763
impl Write for Stdout {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
764
        (&*self).write(buf)
765
    }
S
Steven Fackler 已提交
766
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
767
        (&*self).write_vectored(bufs)
768
    }
769
    #[inline]
S
Steven Fackler 已提交
770
    fn is_write_vectored(&self) -> bool {
771
        io::Write::is_write_vectored(&&*self)
772
    }
773
    fn flush(&mut self) -> io::Result<()> {
774
        (&*self).flush()
775 776
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
777
        (&*self).write_all(buf)
778
    }
779
    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
780
        (&*self).write_all_vectored(bufs)
781
    }
N
Nathan West 已提交
782
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
783
        (&*self).write_fmt(args)
N
Nathan West 已提交
784
    }
785
}
786

787
#[stable(feature = "write_mt", since = "1.48.0")]
788
impl Write for &Stdout {
789 790 791
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.lock().write(buf)
    }
S
Steven Fackler 已提交
792
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
793 794
        self.lock().write_vectored(bufs)
    }
795
    #[inline]
S
Steven Fackler 已提交
796 797
    fn is_write_vectored(&self) -> bool {
        self.lock().is_write_vectored()
798
    }
799 800 801 802 803 804
    fn flush(&mut self) -> io::Result<()> {
        self.lock().flush()
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.lock().write_all(buf)
    }
805 806 807
    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
        self.lock().write_all_vectored(bufs)
    }
N
Nathan West 已提交
808 809 810
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
        self.lock().write_fmt(args)
    }
811
}
812

A
Alex Crichton 已提交
813
#[stable(feature = "rust1", since = "1.0.0")]
814
impl Write for StdoutLock<'_> {
815
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
O
Oliver Middleton 已提交
816
        self.inner.borrow_mut().write(buf)
817
    }
S
Steven Fackler 已提交
818
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
819 820
        self.inner.borrow_mut().write_vectored(bufs)
    }
821
    #[inline]
S
Steven Fackler 已提交
822 823
    fn is_write_vectored(&self) -> bool {
        self.inner.borrow_mut().is_write_vectored()
824
    }
825 826
    fn flush(&mut self) -> io::Result<()> {
        self.inner.borrow_mut().flush()
827
    }
828 829 830 831 832 833
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.inner.borrow_mut().write_all(buf)
    }
    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
        self.inner.borrow_mut().write_all_vectored(bufs)
    }
834 835
}

836
#[stable(feature = "std_debug", since = "1.16.0")]
837
impl fmt::Debug for StdoutLock<'_> {
838
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839
        f.debug_struct("StdoutLock").finish_non_exhaustive()
840 841 842
    }
}

843 844
/// A handle to the standard error stream of a process.
///
T
Tshepang Lekhonkhobe 已提交
845
/// For more information, see the [`io::stderr`] method.
846
///
847
/// [`io::stderr`]: stderr
848 849 850 851 852
///
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
A
Alex Crichton 已提交
853
#[stable(feature = "rust1", since = "1.0.0")]
854
pub struct Stderr {
855
    inner: Pin<&'static ReentrantMutex<RefCell<StderrRaw>>>,
856 857
}

I
Ivan Tham 已提交
858
/// A locked reference to the [`Stderr`] handle.
859
///
I
Ivan Tham 已提交
860
/// This handle implements the [`Write`] trait and is constructed via
861
/// the [`Stderr::lock`] method. See its documentation for more.
862
///
863 864 865 866
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
A
Alex Crichton 已提交
867
#[stable(feature = "rust1", since = "1.0.0")]
868
pub struct StderrLock<'a> {
869
    inner: ReentrantMutexGuard<'a, RefCell<StderrRaw>>,
870 871
}

S
Steve Klabnik 已提交
872 873 874 875
/// Constructs a new handle to the standard error of the current process.
///
/// This handle is not buffered.
///
876 877 878 879 880
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
///
S
Steve Klabnik 已提交
881 882 883 884
/// # Examples
///
/// Using implicit synchronization:
///
885
/// ```no_run
S
Steve Klabnik 已提交
886 887
/// use std::io::{self, Write};
///
888
/// fn main() -> io::Result<()> {
889
///     io::stderr().write_all(b"hello world")?;
S
Steve Klabnik 已提交
890
///
891 892
///     Ok(())
/// }
S
Steve Klabnik 已提交
893 894 895 896
/// ```
///
/// Using explicit synchronization:
///
897
/// ```no_run
S
Steve Klabnik 已提交
898 899
/// use std::io::{self, Write};
///
900 901 902
/// fn main() -> io::Result<()> {
///     let stderr = io::stderr();
///     let mut handle = stderr.lock();
903
///
904
///     handle.write_all(b"hello world")?;
905
///
906 907
///     Ok(())
/// }
S
Steve Klabnik 已提交
908
/// ```
A
Alex Crichton 已提交
909
#[stable(feature = "rust1", since = "1.0.0")]
910
pub fn stderr() -> Stderr {
911 912 913
    // Note that unlike `stdout()` we don't use `at_exit` here to register a
    // destructor. Stderr is not buffered , so there's no need to run a
    // destructor for flushing the buffer
914 915 916
    static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<StderrRaw>>> = SyncOnceCell::new();

    Stderr {
917 918 919 920
        inner: Pin::static_ref(&INSTANCE).get_or_init_pin(
            || unsafe { ReentrantMutex::new(RefCell::new(stderr_raw())) },
            |mutex| unsafe { mutex.init() },
        ),
921
    }
922 923
}

T
Taylor Yu 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
/// Constructs a new locked handle to the standard error of the current
/// process.
///
/// This handle is not buffered.
///
/// ### Note: Windows Portability Consideration
/// When operating in a console, the Windows implementation of this stream does not support
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
/// an error.
///
/// # Example
///
/// ```no_run
/// #![feature(stdio_locked)]
/// use std::io::{self, Write};
///
/// fn main() -> io::Result<()> {
///     let mut handle = io::stderr_locked();
///
///     handle.write_all(b"hello world")?;
///
///     Ok(())
/// }
/// ```
T
Taylor Yu 已提交
948
#[unstable(feature = "stdio_locked", issue = "86845")]
949 950
pub fn stderr_locked() -> StderrLock<'static> {
    stderr().into_locked()
T
Taylor Yu 已提交
951 952
}

953
impl Stderr {
954
    /// Locks this handle to the standard error stream, returning a writable
955 956 957
    /// guard.
    ///
    /// The lock is released when the returned lock goes out of scope. The
958
    /// returned guard also implements the [`Write`] trait for writing data.
G
Guillaume Gomez 已提交
959 960 961 962 963 964 965 966 967 968
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::{self, Write};
    ///
    /// fn foo() -> io::Result<()> {
    ///     let stderr = io::stderr();
    ///     let mut handle = stderr.lock();
    ///
969
    ///     handle.write_all(b"hello world")?;
G
Guillaume Gomez 已提交
970 971 972 973
    ///
    ///     Ok(())
    /// }
    /// ```
A
Alex Crichton 已提交
974
    #[stable(feature = "rust1", since = "1.0.0")]
975
    pub fn lock(&self) -> StderrLock<'_> {
T
Taylor Yu 已提交
976 977 978 979 980 981 982
        self.lock_any()
    }

    // Locks this handle with any lifetime. This depends on the
    // implementation detail that the underlying `ReentrantMutex` is
    // static.
    fn lock_any<'a>(&self) -> StderrLock<'a> {
983
        StderrLock { inner: self.inner.lock() }
984
    }
T
Taylor Yu 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000

    /// Locks and consumes this handle to the standard error stream,
    /// returning a writable guard.
    ///
    /// The lock is released when the returned guard goes out of scope. The
    /// returned guard also implements the [`Write`] trait for writing
    /// data.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(stdio_locked)]
    /// use std::io::{self, Write};
    ///
    /// fn foo() -> io::Result<()> {
    ///     let stderr = io::stderr();
1001
    ///     let mut handle = stderr.into_locked();
T
Taylor Yu 已提交
1002 1003 1004 1005 1006 1007
    ///
    ///     handle.write_all(b"hello world")?;
    ///
    ///     Ok(())
    /// }
    /// ```
T
Taylor Yu 已提交
1008
    #[unstable(feature = "stdio_locked", issue = "86845")]
1009
    pub fn into_locked(self) -> StderrLock<'static> {
T
Taylor Yu 已提交
1010 1011
        self.lock_any()
    }
1012 1013
}

1014
#[stable(feature = "std_debug", since = "1.16.0")]
1015
impl fmt::Debug for Stderr {
1016
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017
        f.debug_struct("Stderr").finish_non_exhaustive()
1018 1019 1020
    }
}

A
Alex Crichton 已提交
1021
#[stable(feature = "rust1", since = "1.0.0")]
1022 1023
impl Write for Stderr {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1024
        (&*self).write(buf)
1025
    }
S
Steven Fackler 已提交
1026
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1027
        (&*self).write_vectored(bufs)
1028
    }
1029
    #[inline]
S
Steven Fackler 已提交
1030
    fn is_write_vectored(&self) -> bool {
1031
        io::Write::is_write_vectored(&&*self)
1032
    }
1033
    fn flush(&mut self) -> io::Result<()> {
1034
        (&*self).flush()
1035 1036
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1037
        (&*self).write_all(buf)
1038
    }
1039
    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
1040
        (&*self).write_all_vectored(bufs)
1041
    }
N
Nathan West 已提交
1042
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
1043
        (&*self).write_fmt(args)
N
Nathan West 已提交
1044
    }
1045
}
1046

1047
#[stable(feature = "write_mt", since = "1.48.0")]
1048
impl Write for &Stderr {
1049 1050 1051
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.lock().write(buf)
    }
S
Steven Fackler 已提交
1052
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1053 1054
        self.lock().write_vectored(bufs)
    }
1055
    #[inline]
S
Steven Fackler 已提交
1056 1057
    fn is_write_vectored(&self) -> bool {
        self.lock().is_write_vectored()
1058
    }
1059 1060 1061 1062 1063 1064
    fn flush(&mut self) -> io::Result<()> {
        self.lock().flush()
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.lock().write_all(buf)
    }
1065 1066 1067
    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
        self.lock().write_all_vectored(bufs)
    }
N
Nathan West 已提交
1068 1069 1070
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
        self.lock().write_fmt(args)
    }
1071
}
1072

A
Alex Crichton 已提交
1073
#[stable(feature = "rust1", since = "1.0.0")]
1074
impl Write for StderrLock<'_> {
1075
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
O
Oliver Middleton 已提交
1076
        self.inner.borrow_mut().write(buf)
1077
    }
S
Steven Fackler 已提交
1078
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1079 1080
        self.inner.borrow_mut().write_vectored(bufs)
    }
1081
    #[inline]
S
Steven Fackler 已提交
1082 1083
    fn is_write_vectored(&self) -> bool {
        self.inner.borrow_mut().is_write_vectored()
1084
    }
1085 1086
    fn flush(&mut self) -> io::Result<()> {
        self.inner.borrow_mut().flush()
1087
    }
1088 1089 1090 1091 1092 1093
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.inner.borrow_mut().write_all(buf)
    }
    fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
        self.inner.borrow_mut().write_all_vectored(bufs)
    }
1094
}
1095

1096
#[stable(feature = "std_debug", since = "1.16.0")]
1097
impl fmt::Debug for StderrLock<'_> {
1098
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099
        f.debug_struct("StderrLock").finish_non_exhaustive()
1100 1101 1102
    }
}

1103
/// Sets the thread-local output capture buffer and returns the old one.
M
Mark Rousskov 已提交
1104
#[unstable(
1105 1106 1107
    feature = "internal_output_capture",
    reason = "this function is meant for use in the test crate \
        and may disappear in the future",
M
Mark Rousskov 已提交
1108 1109
    issue = "none"
)]
1110
#[doc(hidden)]
1111 1112 1113
pub fn set_output_capture(sink: Option<LocalStream>) -> Option<LocalStream> {
    if sink.is_none() && !OUTPUT_CAPTURE_USED.load(Ordering::Relaxed) {
        // OUTPUT_CAPTURE is definitely None since OUTPUT_CAPTURE_USED is false.
M
Mara Bos 已提交
1114 1115
        return None;
    }
1116 1117
    OUTPUT_CAPTURE_USED.store(true, Ordering::Relaxed);
    OUTPUT_CAPTURE.with(move |slot| slot.replace(sink))
1118 1119
}

1120
/// Write `args` to the capture buffer if enabled and possible, or `global_s`
Z
Zack Weinberg 已提交
1121 1122 1123
/// otherwise. `label` identifies the stream in a panic message.
///
/// This function is used to print error messages, so it takes extra
1124
/// care to avoid causing a panic when `local_s` is unusable.
1125 1126
/// For instance, if the TLS key for the local stream is
/// already destroyed, or if the local stream is locked by another
Z
Zack Weinberg 已提交
1127 1128 1129
/// thread, it will just fall back to the global stream.
///
/// However, if the actual I/O causes an error, this function does panic.
1130 1131
fn print_to<T>(args: fmt::Arguments<'_>, global_s: fn() -> T, label: &str)
where
S
Stjepan Glavina 已提交
1132 1133
    T: Write,
{
1134 1135
    if OUTPUT_CAPTURE_USED.load(Ordering::Relaxed)
        && OUTPUT_CAPTURE.try_with(|s| {
1136 1137 1138 1139 1140
            // Note that we completely remove a local sink to write to in case
            // our printing recursively panics/prints, so the recursive
            // panic/print goes to the global sink instead of our local sink.
            s.take().map(|w| {
                let _ = w.lock().unwrap_or_else(|e| e.into_inner()).write_fmt(args);
1141
                s.set(Some(w));
1142 1143 1144
            })
        }) == Ok(Some(()))
    {
1145
        // Succesfully wrote to capture buffer.
1146 1147 1148 1149
        return;
    }

    if let Err(e) = global_s().write_fmt(args) {
Z
Zack Weinberg 已提交
1150
        panic!("failed printing to {}: {}", label, e);
1151 1152
    }
}
S
Steven Fackler 已提交
1153

M
Mark Rousskov 已提交
1154 1155 1156 1157 1158
#[unstable(
    feature = "print_internals",
    reason = "implementation detail which may disappear or be replaced at any time",
    issue = "none"
)]
Z
Zack Weinberg 已提交
1159
#[doc(hidden)]
1160
#[cfg(not(test))]
1161
pub fn _print(args: fmt::Arguments<'_>) {
1162
    print_to(args, stdout, "stdout");
Z
Zack Weinberg 已提交
1163 1164
}

M
Mark Rousskov 已提交
1165 1166 1167 1168 1169
#[unstable(
    feature = "print_internals",
    reason = "implementation detail which may disappear or be replaced at any time",
    issue = "none"
)]
1170
#[doc(hidden)]
1171
#[cfg(not(test))]
1172
pub fn _eprint(args: fmt::Arguments<'_>) {
1173
    print_to(args, stderr, "stderr");
1174 1175
}

1176 1177
#[cfg(test)]
pub use realstd::io::{_eprint, _print};