std/sys/stdio/
unix.rs

1#[cfg(target_os = "hermit")]
2use hermit_abi::{EBADF, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO};
3#[cfg(any(target_family = "unix", target_os = "wasi"))]
4use libc::{EBADF, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO};
5
6use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
7use crate::mem::ManuallyDrop;
8use crate::os::fd::FromRawFd;
9use crate::sys::fd::FileDesc;
10
11pub struct Stdin;
12pub struct Stdout;
13pub struct Stderr;
14
15impl Stdin {
16    pub const fn new() -> Stdin {
17        Stdin
18    }
19}
20
21impl io::Read for Stdin {
22    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
23        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDIN_FILENO)).read(buf) }
24    }
25
26    fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
27        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDIN_FILENO)).read_buf(buf) }
28    }
29
30    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
31        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDIN_FILENO)).read_vectored(bufs) }
32    }
33
34    #[inline]
35    fn is_read_vectored(&self) -> bool {
36        true
37    }
38}
39
40impl Stdout {
41    pub const fn new() -> Stdout {
42        Stdout
43    }
44}
45
46impl io::Write for Stdout {
47    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
48        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDOUT_FILENO)).write(buf) }
49    }
50
51    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
52        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDOUT_FILENO)).write_vectored(bufs) }
53    }
54
55    #[inline]
56    fn is_write_vectored(&self) -> bool {
57        true
58    }
59
60    #[inline]
61    fn flush(&mut self) -> io::Result<()> {
62        Ok(())
63    }
64}
65
66impl Stderr {
67    pub const fn new() -> Stderr {
68        Stderr
69    }
70}
71
72impl io::Write for Stderr {
73    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
74        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDERR_FILENO)).write(buf) }
75    }
76
77    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
78        unsafe { ManuallyDrop::new(FileDesc::from_raw_fd(STDERR_FILENO)).write_vectored(bufs) }
79    }
80
81    #[inline]
82    fn is_write_vectored(&self) -> bool {
83        true
84    }
85
86    #[inline]
87    fn flush(&mut self) -> io::Result<()> {
88        Ok(())
89    }
90}
91
92pub fn is_ebadf(err: &io::Error) -> bool {
93    err.raw_os_error() == Some(EBADF as i32)
94}
95
96pub const STDIN_BUF_SIZE: usize = crate::sys::io::DEFAULT_BUF_SIZE;
97
98pub fn panic_output() -> Option<impl io::Write> {
99    Some(Stderr::new())
100}