StdioExt

Trait StdioExt 

Source
pub trait StdioExt: Sealed {
    // Required methods
    fn set_fd<T: Into<OwnedFd>>(&mut self, fd: T) -> Result<()>;
    fn replace_fd<T: Into<OwnedFd>>(
        &mut self,
        replace_with: T,
    ) -> Result<OwnedFd>;
    fn take_fd(&mut self) -> Result<OwnedFd>;
}
🔬This is a nightly-only experimental API. (stdio_swap #150667)
Available on Unix only.

Required Methods§

Source

fn set_fd<T: Into<OwnedFd>>(&mut self, fd: T) -> Result<()>

🔬This is a nightly-only experimental API. (stdio_swap #150667)

Redirects the stdio file descriptor to point to the file description underpinning fd.

Rust std::io write buffers (if any) are flushed, but other runtimes (e.g. C stdio) or libraries that acquire a clone of the file descriptor will not be aware of this change.

§Platform-specific behavior

This is currently implemented using

  • fd_renumber on wasip1
  • dup2 on most unixes
#![feature(stdio_swap)]
use std::io::{self, Read, Write};
use std::os::unix::io::StdioExt;

fn main() -> io::Result<()> {
   let (reader, mut writer) = io::pipe()?;
   let mut stdin = io::stdin();
   stdin.set_fd(reader)?;
   writer.write_all(b"Hello, world!")?;
   let mut buffer = vec![0; 13];
   assert_eq!(stdin.read(&mut buffer)?, 13);
   assert_eq!(&buffer, b"Hello, world!");
   Ok(())
}
Source

fn replace_fd<T: Into<OwnedFd>>(&mut self, replace_with: T) -> Result<OwnedFd>

🔬This is a nightly-only experimental API. (stdio_swap #150667)

Redirects the stdio file descriptor and returns a new OwnedFd backed by the previous file description.

See set_fd() for details.

Source

fn take_fd(&mut self) -> Result<OwnedFd>

🔬This is a nightly-only experimental API. (stdio_swap #150667)

Redirects the stdio file descriptor to the null device (/dev/null) and returns a new OwnedFd backed by the previous file description.

Programs that communicate structured data via stdio can use this early in main() to extract the fds, treat them as other IO types (File, UnixStream, etc), apply custom buffering or avoid interference from stdio use later in the program.

See set_fd() for additional details.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§