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