std/sys/stdio/
unix.rs

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