use std::os::fd::{BorrowedFd, OwnedFd};
use crate::{Errno, kernel::errno};
pub mod raw;
pub trait Flags: Sized {
const READ: libc::c_int;
const WRITE: libc::c_int;
const BIT: libc::c_int;
fn failure<const SET: bool>(error: Errno) -> Self;
}
pub trait Fd: errno::Source {
fn try_limit() -> Result<(libc::rlim_t, libc::rlim_t), Errno> {
raw::try_limit::<Self>()
}
fn update<E: Flags>(file: BorrowedFd<'_>) -> Result<(), E> {
update::<Self, E, true, true>(file)
}
fn remove<E: Flags>(file: BorrowedFd<'_>) -> Result<(), E> {
update::<Self, E, true, false>(file)
}
fn try_update<E: Flags>(file: BorrowedFd<'_>) -> Result<(), E> {
update::<Self, E, false, true>(file)
}
fn close<E: From<Errno>>(file: OwnedFd) -> Result<(), E> {
raw::close::<Self, E>(file)
}
fn duplicate<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<OwnedFd, E> {
raw::duplicate::<Self, E>(file)
}
fn set<const COMMAND: libc::c_int, E: From<Errno>>(
file: BorrowedFd<'_>,
flags: libc::c_int,
) -> Result<(), E> {
set::<Self, E, COMMAND, false>(file, flags)
}
fn set_retry<const COMMAND: libc::c_int, E: From<Errno>>(
file: BorrowedFd<'_>,
flags: libc::c_int,
) -> Result<(), E> {
set::<Self, E, COMMAND, true>(file, flags)
}
fn read<'a, E: From<Errno>>(
file: BorrowedFd<'_>,
output: &'a mut [u8],
) -> Result<&'a mut [u8], E> {
raw::read::<Self, E>(file, output)
}
fn write<'a, E: From<Errno>>(file: BorrowedFd<'_>, input: &'a [u8]) -> Result<&'a [u8], E> {
raw::try_write::<Self, E>(file, input)
}
}
impl<S: errno::Source> Fd for S {}
fn update<S: Fd + ?Sized, E: Flags, const RETRY: bool, const ENABLED: bool>(
file: BorrowedFd<'_>,
) -> Result<(), E> {
let flags = raw::flags::<S, E, false, RETRY>(file, 0).map_err(E::failure::<false>)?;
let flags = if ENABLED {
flags | E::BIT
} else {
flags & !E::BIT
};
raw::flags::<S, E, true, RETRY>(file, flags).map_err(E::failure::<true>)?;
Ok(())
}
fn set<S: Fd + ?Sized, E: From<Errno>, const COMMAND: libc::c_int, const RETRY: bool>(
file: BorrowedFd<'_>,
flags: libc::c_int,
) -> Result<(), E> {
const { assert!(COMMAND == libc::F_SETFD || COMMAND == libc::F_SETFL) };
if COMMAND == libc::F_SETFD {
raw::flags::<S, crate::Cloexec, true, RETRY>(file, flags)?;
} else {
raw::flags::<S, crate::Nonblock, true, RETRY>(file, flags)?;
}
Ok(())
}