Skip to content

Commit 60f6cbd

Browse files
committed
wasi: Use raw syscalls for stdio
I've since learned that the mapping between libc fds and wasi fds are expected to be one-to-one, so we can use the raw syscalls for writing to stdout/stderr and reading from stdin! This should help ensure that we don't depend on a C library too unnecessarily.
1 parent 382f9a7 commit 60f6cbd

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

src/libstd/sys/wasi/stdio.rs

+9-14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
use crate::io;
1+
use crate::io::{self, IoVec, IoVecMut};
22
use crate::libc;
3-
use crate::sys::cvt;
3+
use crate::mem::ManuallyDrop;
4+
use crate::sys::fd::WasiFd;
45

56
pub struct Stdin;
67
pub struct Stdout;
@@ -12,10 +13,8 @@ impl Stdin {
1213
}
1314

1415
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
15-
let amt = cvt(unsafe {
16-
libc::read(libc::STDIN_FILENO, data.as_mut_ptr() as *mut _, data.len())
17-
})?;
18-
Ok(amt as usize)
16+
ManuallyDrop::new(unsafe { WasiFd::from_raw(libc::STDIN_FILENO as u32) })
17+
.read(&mut [IoVecMut::new(data)])
1918
}
2019
}
2120

@@ -25,10 +24,8 @@ impl Stdout {
2524
}
2625

2726
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
28-
let amt = cvt(unsafe {
29-
libc::write(libc::STDOUT_FILENO, data.as_ptr() as *const _, data.len())
30-
})?;
31-
Ok(amt as usize)
27+
ManuallyDrop::new(unsafe { WasiFd::from_raw(libc::STDOUT_FILENO as u32) })
28+
.write(&[IoVec::new(data)])
3229
}
3330

3431
pub fn flush(&self) -> io::Result<()> {
@@ -42,10 +39,8 @@ impl Stderr {
4239
}
4340

4441
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
45-
let amt = cvt(unsafe {
46-
libc::write(libc::STDERR_FILENO, data.as_ptr() as *const _, data.len())
47-
})?;
48-
Ok(amt as usize)
42+
ManuallyDrop::new(unsafe { WasiFd::from_raw(libc::STDERR_FILENO as u32) })
43+
.write(&[IoVec::new(data)])
4944
}
5045

5146
pub fn flush(&self) -> io::Result<()> {

0 commit comments

Comments
 (0)