]> git.proxmox.com Git - rustc.git/blob - src/libstd/io/stdio.rs
New upstream version 1.45.0+dfsg1
[rustc.git] / src / libstd / io / stdio.rs
1 #![cfg_attr(test, allow(unused))]
2
3 use crate::io::prelude::*;
4
5 use crate::cell::RefCell;
6 use crate::fmt;
7 use crate::io::lazy::Lazy;
8 use crate::io::{self, BufReader, Initializer, IoSlice, IoSliceMut, LineWriter};
9 use crate::sync::{Arc, Mutex, MutexGuard, Once};
10 use crate::sys::stdio;
11 use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
12 use crate::thread::LocalKey;
13
14 thread_local! {
15 /// Stdout used by print! and println! macros
16 static LOCAL_STDOUT: RefCell<Option<Box<dyn Write + Send>>> = {
17 RefCell::new(None)
18 }
19 }
20
21 thread_local! {
22 /// Stderr used by eprint! and eprintln! macros, and panics
23 static LOCAL_STDERR: RefCell<Option<Box<dyn Write + Send>>> = {
24 RefCell::new(None)
25 }
26 }
27
28 /// A handle to a raw instance of the standard input stream of this process.
29 ///
30 /// This handle is not synchronized or buffered in any fashion. Constructed via
31 /// the `std::io::stdio::stdin_raw` function.
32 struct StdinRaw(stdio::Stdin);
33
34 /// A handle to a raw instance of the standard output stream of this process.
35 ///
36 /// This handle is not synchronized or buffered in any fashion. Constructed via
37 /// the `std::io::stdio::stdout_raw` function.
38 struct StdoutRaw(stdio::Stdout);
39
40 /// A handle to a raw instance of the standard output stream of this process.
41 ///
42 /// This handle is not synchronized or buffered in any fashion. Constructed via
43 /// the `std::io::stdio::stderr_raw` function.
44 struct StderrRaw(stdio::Stderr);
45
46 /// Constructs a new raw handle to the standard input of this process.
47 ///
48 /// The returned handle does not interact with any other handles created nor
49 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
50 /// handles is **not** available to raw handles returned from this function.
51 ///
52 /// The returned handle has no external synchronization or buffering.
53 fn stdin_raw() -> io::Result<StdinRaw> {
54 stdio::Stdin::new().map(StdinRaw)
55 }
56
57 /// Constructs a new raw handle to the standard output stream of this process.
58 ///
59 /// The returned handle does not interact with any other handles created nor
60 /// handles returned by `std::io::stdout`. Note that data is buffered by the
61 /// `std::io::stdout` handles so writes which happen via this raw handle may
62 /// appear before previous writes.
63 ///
64 /// The returned handle has no external synchronization or buffering layered on
65 /// top.
66 fn stdout_raw() -> io::Result<StdoutRaw> {
67 stdio::Stdout::new().map(StdoutRaw)
68 }
69
70 /// Constructs a new raw handle to the standard error stream of this process.
71 ///
72 /// The returned handle does not interact with any other handles created nor
73 /// handles returned by `std::io::stderr`.
74 ///
75 /// The returned handle has no external synchronization or buffering layered on
76 /// top.
77 fn stderr_raw() -> io::Result<StderrRaw> {
78 stdio::Stderr::new().map(StderrRaw)
79 }
80
81 impl Read for StdinRaw {
82 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
83 self.0.read(buf)
84 }
85
86 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
87 self.0.read_vectored(bufs)
88 }
89
90 #[inline]
91 fn is_read_vectored(&self) -> bool {
92 self.0.is_read_vectored()
93 }
94
95 #[inline]
96 unsafe fn initializer(&self) -> Initializer {
97 Initializer::nop()
98 }
99 }
100 impl Write for StdoutRaw {
101 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
102 self.0.write(buf)
103 }
104
105 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
106 self.0.write_vectored(bufs)
107 }
108
109 #[inline]
110 fn is_write_vectored(&self) -> bool {
111 self.0.is_write_vectored()
112 }
113
114 fn flush(&mut self) -> io::Result<()> {
115 self.0.flush()
116 }
117 }
118 impl Write for StderrRaw {
119 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
120 self.0.write(buf)
121 }
122
123 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
124 self.0.write_vectored(bufs)
125 }
126
127 #[inline]
128 fn is_write_vectored(&self) -> bool {
129 self.0.is_write_vectored()
130 }
131
132 fn flush(&mut self) -> io::Result<()> {
133 self.0.flush()
134 }
135 }
136
137 enum Maybe<T> {
138 Real(T),
139 Fake,
140 }
141
142 impl<W: io::Write> io::Write for Maybe<W> {
143 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
144 match *self {
145 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
146 Maybe::Fake => Ok(buf.len()),
147 }
148 }
149
150 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
151 let total = bufs.iter().map(|b| b.len()).sum();
152 match self {
153 Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
154 Maybe::Fake => Ok(total),
155 }
156 }
157
158 #[inline]
159 fn is_write_vectored(&self) -> bool {
160 match self {
161 Maybe::Real(w) => w.is_write_vectored(),
162 Maybe::Fake => true,
163 }
164 }
165
166 fn flush(&mut self) -> io::Result<()> {
167 match *self {
168 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
169 Maybe::Fake => Ok(()),
170 }
171 }
172 }
173
174 impl<R: io::Read> io::Read for Maybe<R> {
175 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
176 match *self {
177 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
178 Maybe::Fake => Ok(0),
179 }
180 }
181
182 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
183 match self {
184 Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
185 Maybe::Fake => Ok(0),
186 }
187 }
188
189 #[inline]
190 fn is_read_vectored(&self) -> bool {
191 match self {
192 Maybe::Real(w) => w.is_read_vectored(),
193 Maybe::Fake => true,
194 }
195 }
196 }
197
198 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
199 match r {
200 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
201 r => r,
202 }
203 }
204
205 /// A handle to the standard input stream of a process.
206 ///
207 /// Each handle is a shared reference to a global buffer of input data to this
208 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
209 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
210 /// to other reads.
211 ///
212 /// This handle implements the `Read` trait, but beware that concurrent reads
213 /// of `Stdin` must be executed with care.
214 ///
215 /// Created by the [`io::stdin`] method.
216 ///
217 /// [`io::stdin`]: fn.stdin.html
218 /// [`BufRead`]: trait.BufRead.html
219 ///
220 /// ### Note: Windows Portability Consideration
221 /// When operating in a console, the Windows implementation of this stream does not support
222 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
223 /// an error.
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub struct Stdin {
226 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
227 }
228
229 /// A locked reference to the `Stdin` handle.
230 ///
231 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
232 /// is constructed via the [`Stdin::lock`] method.
233 ///
234 /// [`Read`]: trait.Read.html
235 /// [`BufRead`]: trait.BufRead.html
236 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
237 ///
238 /// ### Note: Windows Portability Consideration
239 /// When operating in a console, the Windows implementation of this stream does not support
240 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
241 /// an error.
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub struct StdinLock<'a> {
244 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
245 }
246
247 /// Constructs a new handle to the standard input of the current process.
248 ///
249 /// Each handle returned is a reference to a shared global buffer whose access
250 /// is synchronized via a mutex. If you need more explicit control over
251 /// locking, see the [`Stdin::lock`] method.
252 ///
253 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
254 ///
255 /// ### Note: Windows Portability Consideration
256 /// When operating in a console, the Windows implementation of this stream does not support
257 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
258 /// an error.
259 ///
260 /// # Examples
261 ///
262 /// Using implicit synchronization:
263 ///
264 /// ```no_run
265 /// use std::io::{self, Read};
266 ///
267 /// fn main() -> io::Result<()> {
268 /// let mut buffer = String::new();
269 /// io::stdin().read_to_string(&mut buffer)?;
270 /// Ok(())
271 /// }
272 /// ```
273 ///
274 /// Using explicit synchronization:
275 ///
276 /// ```no_run
277 /// use std::io::{self, Read};
278 ///
279 /// fn main() -> io::Result<()> {
280 /// let mut buffer = String::new();
281 /// let stdin = io::stdin();
282 /// let mut handle = stdin.lock();
283 ///
284 /// handle.read_to_string(&mut buffer)?;
285 /// Ok(())
286 /// }
287 /// ```
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn stdin() -> Stdin {
290 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
291 return Stdin {
292 inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
293 };
294
295 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
296 // This must not reentrantly access `INSTANCE`
297 let stdin = match stdin_raw() {
298 Ok(stdin) => Maybe::Real(stdin),
299 _ => Maybe::Fake,
300 };
301
302 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
303 }
304 }
305
306 impl Stdin {
307 /// Locks this handle to the standard input stream, returning a readable
308 /// guard.
309 ///
310 /// The lock is released when the returned lock goes out of scope. The
311 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
312 /// accessing the underlying data.
313 ///
314 /// [`Read`]: trait.Read.html
315 /// [`BufRead`]: trait.BufRead.html
316 ///
317 /// # Examples
318 ///
319 /// ```no_run
320 /// use std::io::{self, Read};
321 ///
322 /// fn main() -> io::Result<()> {
323 /// let mut buffer = String::new();
324 /// let stdin = io::stdin();
325 /// let mut handle = stdin.lock();
326 ///
327 /// handle.read_to_string(&mut buffer)?;
328 /// Ok(())
329 /// }
330 /// ```
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn lock(&self) -> StdinLock<'_> {
333 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
334 }
335
336 /// Locks this handle and reads a line of input, appending it to the specified buffer.
337 ///
338 /// For detailed semantics of this method, see the documentation on
339 /// [`BufRead::read_line`].
340 ///
341 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
342 ///
343 /// # Examples
344 ///
345 /// ```no_run
346 /// use std::io;
347 ///
348 /// let mut input = String::new();
349 /// match io::stdin().read_line(&mut input) {
350 /// Ok(n) => {
351 /// println!("{} bytes read", n);
352 /// println!("{}", input);
353 /// }
354 /// Err(error) => println!("error: {}", error),
355 /// }
356 /// ```
357 ///
358 /// You can run the example one of two ways:
359 ///
360 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
361 /// - Give it text interactively by running the executable directly,
362 /// in which case it will wait for the Enter key to be pressed before
363 /// continuing
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
366 self.lock().read_line(buf)
367 }
368 }
369
370 #[stable(feature = "std_debug", since = "1.16.0")]
371 impl fmt::Debug for Stdin {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 f.pad("Stdin { .. }")
374 }
375 }
376
377 #[stable(feature = "rust1", since = "1.0.0")]
378 impl Read for Stdin {
379 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
380 self.lock().read(buf)
381 }
382 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
383 self.lock().read_vectored(bufs)
384 }
385 #[inline]
386 fn is_read_vectored(&self) -> bool {
387 self.lock().is_read_vectored()
388 }
389 #[inline]
390 unsafe fn initializer(&self) -> Initializer {
391 Initializer::nop()
392 }
393 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
394 self.lock().read_to_end(buf)
395 }
396 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
397 self.lock().read_to_string(buf)
398 }
399 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
400 self.lock().read_exact(buf)
401 }
402 }
403
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl Read for StdinLock<'_> {
406 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
407 self.inner.read(buf)
408 }
409
410 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
411 self.inner.read_vectored(bufs)
412 }
413
414 #[inline]
415 fn is_read_vectored(&self) -> bool {
416 self.inner.is_read_vectored()
417 }
418
419 #[inline]
420 unsafe fn initializer(&self) -> Initializer {
421 Initializer::nop()
422 }
423 }
424
425 #[stable(feature = "rust1", since = "1.0.0")]
426 impl BufRead for StdinLock<'_> {
427 fn fill_buf(&mut self) -> io::Result<&[u8]> {
428 self.inner.fill_buf()
429 }
430 fn consume(&mut self, n: usize) {
431 self.inner.consume(n)
432 }
433 }
434
435 #[stable(feature = "std_debug", since = "1.16.0")]
436 impl fmt::Debug for StdinLock<'_> {
437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438 f.pad("StdinLock { .. }")
439 }
440 }
441
442 /// A handle to the global standard output stream of the current process.
443 ///
444 /// Each handle shares a global buffer of data to be written to the standard
445 /// output stream. Access is also synchronized via a lock and explicit control
446 /// over locking is available via the [`lock`] method.
447 ///
448 /// Created by the [`io::stdout`] method.
449 ///
450 /// ### Note: Windows Portability Consideration
451 /// When operating in a console, the Windows implementation of this stream does not support
452 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
453 /// an error.
454 ///
455 /// [`lock`]: #method.lock
456 /// [`io::stdout`]: fn.stdout.html
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub struct Stdout {
459 // FIXME: this should be LineWriter or BufWriter depending on the state of
460 // stdout (tty or not). Note that if this is not line buffered it
461 // should also flush-on-panic or some form of flush-on-abort.
462 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
463 }
464
465 /// A locked reference to the `Stdout` handle.
466 ///
467 /// This handle implements the [`Write`] trait, and is constructed via
468 /// the [`Stdout::lock`] method.
469 ///
470 /// ### Note: Windows Portability Consideration
471 /// When operating in a console, the Windows implementation of this stream does not support
472 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
473 /// an error.
474 ///
475 /// [`Write`]: trait.Write.html
476 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub struct StdoutLock<'a> {
479 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
480 }
481
482 /// Constructs a new handle to the standard output of the current process.
483 ///
484 /// Each handle returned is a reference to a shared global buffer whose access
485 /// is synchronized via a mutex. If you need more explicit control over
486 /// locking, see the [`Stdout::lock`] method.
487 ///
488 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
489 ///
490 /// ### Note: Windows Portability Consideration
491 /// When operating in a console, the Windows implementation of this stream does not support
492 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
493 /// an error.
494 ///
495 /// # Examples
496 ///
497 /// Using implicit synchronization:
498 ///
499 /// ```no_run
500 /// use std::io::{self, Write};
501 ///
502 /// fn main() -> io::Result<()> {
503 /// io::stdout().write_all(b"hello world")?;
504 ///
505 /// Ok(())
506 /// }
507 /// ```
508 ///
509 /// Using explicit synchronization:
510 ///
511 /// ```no_run
512 /// use std::io::{self, Write};
513 ///
514 /// fn main() -> io::Result<()> {
515 /// let stdout = io::stdout();
516 /// let mut handle = stdout.lock();
517 ///
518 /// handle.write_all(b"hello world")?;
519 ///
520 /// Ok(())
521 /// }
522 /// ```
523 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn stdout() -> Stdout {
525 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
526 return Stdout {
527 inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
528 };
529
530 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
531 // This must not reentrantly access `INSTANCE`
532 let stdout = match stdout_raw() {
533 Ok(stdout) => Maybe::Real(stdout),
534 _ => Maybe::Fake,
535 };
536 unsafe {
537 let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
538 ret.init();
539 ret
540 }
541 }
542 }
543
544 impl Stdout {
545 /// Locks this handle to the standard output stream, returning a writable
546 /// guard.
547 ///
548 /// The lock is released when the returned lock goes out of scope. The
549 /// returned guard also implements the `Write` trait for writing data.
550 ///
551 /// # Examples
552 ///
553 /// ```no_run
554 /// use std::io::{self, Write};
555 ///
556 /// fn main() -> io::Result<()> {
557 /// let stdout = io::stdout();
558 /// let mut handle = stdout.lock();
559 ///
560 /// handle.write_all(b"hello world")?;
561 ///
562 /// Ok(())
563 /// }
564 /// ```
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn lock(&self) -> StdoutLock<'_> {
567 StdoutLock { inner: self.inner.lock() }
568 }
569 }
570
571 #[stable(feature = "std_debug", since = "1.16.0")]
572 impl fmt::Debug for Stdout {
573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574 f.pad("Stdout { .. }")
575 }
576 }
577
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl Write for Stdout {
580 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
581 self.lock().write(buf)
582 }
583 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
584 self.lock().write_vectored(bufs)
585 }
586 #[inline]
587 fn is_write_vectored(&self) -> bool {
588 self.lock().is_write_vectored()
589 }
590 fn flush(&mut self) -> io::Result<()> {
591 self.lock().flush()
592 }
593 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
594 self.lock().write_all(buf)
595 }
596 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
597 self.lock().write_fmt(args)
598 }
599 }
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl Write for StdoutLock<'_> {
602 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
603 self.inner.borrow_mut().write(buf)
604 }
605 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
606 self.inner.borrow_mut().write_vectored(bufs)
607 }
608 #[inline]
609 fn is_write_vectored(&self) -> bool {
610 self.inner.borrow_mut().is_write_vectored()
611 }
612 fn flush(&mut self) -> io::Result<()> {
613 self.inner.borrow_mut().flush()
614 }
615 }
616
617 #[stable(feature = "std_debug", since = "1.16.0")]
618 impl fmt::Debug for StdoutLock<'_> {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 f.pad("StdoutLock { .. }")
621 }
622 }
623
624 /// A handle to the standard error stream of a process.
625 ///
626 /// For more information, see the [`io::stderr`] method.
627 ///
628 /// [`io::stderr`]: fn.stderr.html
629 ///
630 /// ### Note: Windows Portability Consideration
631 /// When operating in a console, the Windows implementation of this stream does not support
632 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
633 /// an error.
634 #[stable(feature = "rust1", since = "1.0.0")]
635 pub struct Stderr {
636 inner: &'static ReentrantMutex<RefCell<Maybe<StderrRaw>>>,
637 }
638
639 /// A locked reference to the `Stderr` handle.
640 ///
641 /// This handle implements the `Write` trait and is constructed via
642 /// the [`Stderr::lock`] method.
643 ///
644 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
645 ///
646 /// ### Note: Windows Portability Consideration
647 /// When operating in a console, the Windows implementation of this stream does not support
648 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
649 /// an error.
650 #[stable(feature = "rust1", since = "1.0.0")]
651 pub struct StderrLock<'a> {
652 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
653 }
654
655 /// Constructs a new handle to the standard error of the current process.
656 ///
657 /// This handle is not buffered.
658 ///
659 /// ### Note: Windows Portability Consideration
660 /// When operating in a console, the Windows implementation of this stream does not support
661 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
662 /// an error.
663 ///
664 /// # Examples
665 ///
666 /// Using implicit synchronization:
667 ///
668 /// ```no_run
669 /// use std::io::{self, Write};
670 ///
671 /// fn main() -> io::Result<()> {
672 /// io::stderr().write_all(b"hello world")?;
673 ///
674 /// Ok(())
675 /// }
676 /// ```
677 ///
678 /// Using explicit synchronization:
679 ///
680 /// ```no_run
681 /// use std::io::{self, Write};
682 ///
683 /// fn main() -> io::Result<()> {
684 /// let stderr = io::stderr();
685 /// let mut handle = stderr.lock();
686 ///
687 /// handle.write_all(b"hello world")?;
688 ///
689 /// Ok(())
690 /// }
691 /// ```
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn stderr() -> Stderr {
694 // Note that unlike `stdout()` we don't use `Lazy` here which registers a
695 // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
696 // any owned resources, so there's no need to run any destructors at some
697 // point in the future.
698 //
699 // This has the added benefit of allowing `stderr` to be usable during
700 // process shutdown as well!
701 static INSTANCE: ReentrantMutex<RefCell<Maybe<StderrRaw>>> =
702 unsafe { ReentrantMutex::new(RefCell::new(Maybe::Fake)) };
703
704 // When accessing stderr we need one-time initialization of the reentrant
705 // mutex, followed by one-time detection of whether we actually have a
706 // stderr handle or not. Afterwards we can just always use the now-filled-in
707 // `INSTANCE` value.
708 static INIT: Once = Once::new();
709 INIT.call_once(|| unsafe {
710 INSTANCE.init();
711 if let Ok(stderr) = stderr_raw() {
712 *INSTANCE.lock().borrow_mut() = Maybe::Real(stderr);
713 }
714 });
715 Stderr { inner: &INSTANCE }
716 }
717
718 impl Stderr {
719 /// Locks this handle to the standard error stream, returning a writable
720 /// guard.
721 ///
722 /// The lock is released when the returned lock goes out of scope. The
723 /// returned guard also implements the `Write` trait for writing data.
724 ///
725 /// # Examples
726 ///
727 /// ```
728 /// use std::io::{self, Write};
729 ///
730 /// fn foo() -> io::Result<()> {
731 /// let stderr = io::stderr();
732 /// let mut handle = stderr.lock();
733 ///
734 /// handle.write_all(b"hello world")?;
735 ///
736 /// Ok(())
737 /// }
738 /// ```
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub fn lock(&self) -> StderrLock<'_> {
741 StderrLock { inner: self.inner.lock() }
742 }
743 }
744
745 #[stable(feature = "std_debug", since = "1.16.0")]
746 impl fmt::Debug for Stderr {
747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748 f.pad("Stderr { .. }")
749 }
750 }
751
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl Write for Stderr {
754 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
755 self.lock().write(buf)
756 }
757 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
758 self.lock().write_vectored(bufs)
759 }
760 #[inline]
761 fn is_write_vectored(&self) -> bool {
762 self.lock().is_write_vectored()
763 }
764 fn flush(&mut self) -> io::Result<()> {
765 self.lock().flush()
766 }
767 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
768 self.lock().write_all(buf)
769 }
770 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
771 self.lock().write_fmt(args)
772 }
773 }
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl Write for StderrLock<'_> {
776 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
777 self.inner.borrow_mut().write(buf)
778 }
779 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
780 self.inner.borrow_mut().write_vectored(bufs)
781 }
782 #[inline]
783 fn is_write_vectored(&self) -> bool {
784 self.inner.borrow_mut().is_write_vectored()
785 }
786 fn flush(&mut self) -> io::Result<()> {
787 self.inner.borrow_mut().flush()
788 }
789 }
790
791 #[stable(feature = "std_debug", since = "1.16.0")]
792 impl fmt::Debug for StderrLock<'_> {
793 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794 f.pad("StderrLock { .. }")
795 }
796 }
797
798 /// Resets the thread-local stderr handle to the specified writer
799 ///
800 /// This will replace the current thread's stderr handle, returning the old
801 /// handle. All future calls to `panic!` and friends will emit their output to
802 /// this specified handle.
803 ///
804 /// Note that this does not need to be called for all new threads; the default
805 /// output handle is to the process's stderr stream.
806 #[unstable(
807 feature = "set_stdio",
808 reason = "this function may disappear completely or be replaced \
809 with a more general mechanism",
810 issue = "none"
811 )]
812 #[doc(hidden)]
813 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
814 use crate::mem;
815 LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
816 let _ = s.flush();
817 Some(s)
818 })
819 }
820
821 /// Resets the thread-local stdout handle to the specified writer
822 ///
823 /// This will replace the current thread's stdout handle, returning the old
824 /// handle. All future calls to `print!` and friends will emit their output to
825 /// this specified handle.
826 ///
827 /// Note that this does not need to be called for all new threads; the default
828 /// output handle is to the process's stdout stream.
829 #[unstable(
830 feature = "set_stdio",
831 reason = "this function may disappear completely or be replaced \
832 with a more general mechanism",
833 issue = "none"
834 )]
835 #[doc(hidden)]
836 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
837 use crate::mem;
838 LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
839 let _ = s.flush();
840 Some(s)
841 })
842 }
843
844 /// Write `args` to output stream `local_s` if possible, `global_s`
845 /// otherwise. `label` identifies the stream in a panic message.
846 ///
847 /// This function is used to print error messages, so it takes extra
848 /// care to avoid causing a panic when `local_s` is unusable.
849 /// For instance, if the TLS key for the local stream is
850 /// already destroyed, or if the local stream is locked by another
851 /// thread, it will just fall back to the global stream.
852 ///
853 /// However, if the actual I/O causes an error, this function does panic.
854 fn print_to<T>(
855 args: fmt::Arguments<'_>,
856 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
857 global_s: fn() -> T,
858 label: &str,
859 ) where
860 T: Write,
861 {
862 let result = local_s
863 .try_with(|s| {
864 // Note that we completely remove a local sink to write to in case
865 // our printing recursively panics/prints, so the recursive
866 // panic/print goes to the global sink instead of our local sink.
867 let prev = s.borrow_mut().take();
868 if let Some(mut w) = prev {
869 let result = w.write_fmt(args);
870 *s.borrow_mut() = Some(w);
871 return result;
872 }
873 global_s().write_fmt(args)
874 })
875 .unwrap_or_else(|_| global_s().write_fmt(args));
876
877 if let Err(e) = result {
878 panic!("failed printing to {}: {}", label, e);
879 }
880 }
881
882 #[unstable(
883 feature = "print_internals",
884 reason = "implementation detail which may disappear or be replaced at any time",
885 issue = "none"
886 )]
887 #[doc(hidden)]
888 #[cfg(not(test))]
889 pub fn _print(args: fmt::Arguments<'_>) {
890 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
891 }
892
893 #[unstable(
894 feature = "print_internals",
895 reason = "implementation detail which may disappear or be replaced at any time",
896 issue = "none"
897 )]
898 #[doc(hidden)]
899 #[cfg(not(test))]
900 pub fn _eprint(args: fmt::Arguments<'_>) {
901 print_to(args, &LOCAL_STDERR, stderr, "stderr");
902 }
903
904 #[cfg(test)]
905 pub use realstd::io::{_eprint, _print};
906
907 #[cfg(test)]
908 mod tests {
909 use super::*;
910 use crate::panic::{RefUnwindSafe, UnwindSafe};
911 use crate::thread;
912
913 #[test]
914 fn stdout_unwind_safe() {
915 assert_unwind_safe::<Stdout>();
916 }
917 #[test]
918 fn stdoutlock_unwind_safe() {
919 assert_unwind_safe::<StdoutLock<'_>>();
920 assert_unwind_safe::<StdoutLock<'static>>();
921 }
922 #[test]
923 fn stderr_unwind_safe() {
924 assert_unwind_safe::<Stderr>();
925 }
926 #[test]
927 fn stderrlock_unwind_safe() {
928 assert_unwind_safe::<StderrLock<'_>>();
929 assert_unwind_safe::<StderrLock<'static>>();
930 }
931
932 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
933
934 #[test]
935 #[cfg_attr(target_os = "emscripten", ignore)]
936 fn panic_doesnt_poison() {
937 thread::spawn(|| {
938 let _a = stdin();
939 let _a = _a.lock();
940 let _a = stdout();
941 let _a = _a.lock();
942 let _a = stderr();
943 let _a = _a.lock();
944 panic!();
945 })
946 .join()
947 .unwrap_err();
948
949 let _a = stdin();
950 let _a = _a.lock();
951 let _a = stdout();
952 let _a = _a.lock();
953 let _a = stderr();
954 let _a = _a.lock();
955 }
956 }