149 lines
3.0 KiB
Rust

use std::{
io::{self, Read, Stdin, Write},
ops::{Deref, DerefMut},
os::fd::{AsRawFd, RawFd},
process::Stdio,
time::Duration,
};
use crate::sys::{
self, PidFd as SysPidFd, Pipe as SysPipe, Poll as SysPoll, RawStdin as SysRawStdin,
TimerFd as SysTimerFd,
};
use self::sys::PipeImpl;
#[repr(transparent)]
pub struct Poll(sys::PollImpl);
#[repr(transparent)]
pub struct TimerFd(sys::TimerFdImpl);
#[repr(transparent)]
pub struct PidFd(sys::PidFdImpl);
#[repr(transparent)]
pub struct Pipe(sys::PipeImpl);
#[repr(transparent)]
pub struct RawStdin<'a>(sys::RawStdinImpl<'a>);
impl Poll {
pub fn new() -> io::Result<Self> {
sys::PollImpl::new().map(Self)
}
pub fn add<F: AsRawFd>(&mut self, interest: &F) -> io::Result<()> {
self.0.add(interest)
}
pub fn remove<F: AsRawFd>(&mut self, interest: &F) -> io::Result<()> {
self.0.remove(interest)
}
pub fn wait(&mut self, timeout: Option<Duration>) -> io::Result<Option<RawFd>> {
self.0.wait(timeout)
}
}
impl AsRawFd for Poll {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl TimerFd {
pub fn new() -> io::Result<Self> {
sys::TimerFdImpl::new().map(Self)
}
pub fn start(&mut self, timeout: Duration) -> io::Result<()> {
self.0.start(timeout)
}
pub fn is_expired(&mut self) -> io::Result<bool> {
self.0.is_expired()
}
}
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl PidFd {
pub fn new(pid: u32) -> io::Result<Self> {
sys::PidFdImpl::new(pid).map(Self)
}
pub fn exit_status(&self) -> io::Result<i32> {
self.0.exit_status()
}
}
impl AsRawFd for PidFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl Pipe {
pub fn new(read_nonblocking: bool, write_nonblocking: bool) -> io::Result<(Self, Self)> {
let (read, write) = PipeImpl::new(read_nonblocking, write_nonblocking)?;
Ok((Self(read), Self(write)))
}
pub fn to_child_stdio(&self) -> Stdio {
self.0.to_child_stdio()
}
}
impl Read for Pipe {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for Pipe {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
impl AsRawFd for Pipe {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl<'a> RawStdin<'a> {
pub fn new(stdin: &'a mut Stdin) -> io::Result<Self> {
sys::RawStdinImpl::new(stdin).map(Self)
}
}
impl Deref for RawStdin<'_> {
type Target = Stdin;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl DerefMut for RawStdin<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
impl AsRawFd for RawStdin<'_> {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}