]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/wasi/stdio.rs
Rollup merge of #82686 - CDirkx:unix-platform, r=m-ou-se
[rust.git] / library / std / src / sys / wasi / stdio.rs
1 #![deny(unsafe_op_in_unsafe_fn)]
2
3 use super::fd::WasiFd;
4 use crate::io::{self, IoSlice, IoSliceMut};
5 use crate::mem::ManuallyDrop;
6
7 pub struct Stdin;
8 pub struct Stdout;
9 pub struct Stderr;
10
11 impl Stdin {
12     pub const fn new() -> Stdin {
13         Stdin
14     }
15
16     #[inline]
17     pub fn as_raw_fd(&self) -> u32 {
18         0
19     }
20 }
21
22 impl io::Read for Stdin {
23     fn read(&mut self, data: &mut [u8]) -> io::Result<usize> {
24         self.read_vectored(&mut [IoSliceMut::new(data)])
25     }
26
27     fn read_vectored(&mut self, data: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
28         ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).read(data)
29     }
30
31     #[inline]
32     fn is_read_vectored(&self) -> bool {
33         true
34     }
35 }
36
37 impl Stdout {
38     pub const fn new() -> Stdout {
39         Stdout
40     }
41
42     #[inline]
43     pub fn as_raw_fd(&self) -> u32 {
44         1
45     }
46 }
47
48 impl io::Write for Stdout {
49     fn write(&mut self, data: &[u8]) -> io::Result<usize> {
50         self.write_vectored(&[IoSlice::new(data)])
51     }
52
53     fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> {
54         ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).write(data)
55     }
56
57     #[inline]
58     fn is_write_vectored(&self) -> bool {
59         true
60     }
61     fn flush(&mut self) -> io::Result<()> {
62         Ok(())
63     }
64 }
65
66 impl Stderr {
67     pub const fn new() -> Stderr {
68         Stderr
69     }
70
71     #[inline]
72     pub fn as_raw_fd(&self) -> u32 {
73         2
74     }
75 }
76
77 impl io::Write for Stderr {
78     fn write(&mut self, data: &[u8]) -> io::Result<usize> {
79         self.write_vectored(&[IoSlice::new(data)])
80     }
81
82     fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> {
83         ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).write(data)
84     }
85
86     #[inline]
87     fn is_write_vectored(&self) -> bool {
88         true
89     }
90
91     fn flush(&mut self) -> io::Result<()> {
92         Ok(())
93     }
94 }
95
96 pub const STDIN_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
97
98 pub fn is_ebadf(err: &io::Error) -> bool {
99     err.raw_os_error() == Some(wasi::ERRNO_BADF.into())
100 }
101
102 pub fn panic_output() -> Option<impl io::Write> {
103     Some(Stderr::new())
104 }