use std::{
mem::MaybeUninit,
os::fd::{self, AsRawFd as _, BorrowedFd, IntoRawFd as _, OwnedFd},
};
use crate::{Errno, io, kernel};
use kernel::errno;
pub(super) fn try_limit<S: errno::Source + ?Sized>() -> Result<(libc::rlim_t, libc::rlim_t), Errno>
{
let mut limit = MaybeUninit::uninit();
let limit = unsafe {
let status = libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr());
kernel::raw::Status::new(status).try_zero::<S, Errno>()?;
limit.assume_init()
};
Ok((limit.rlim_cur, limit.rlim_max))
}
pub(super) fn close<S: errno::Source + ?Sized, E: From<Errno>>(file: OwnedFd) -> Result<(), E> {
unsafe { kernel::raw::Status::new(libc::close(file.into_raw_fd())).try_zero::<S, E>() }
}
pub(super) fn duplicate<S: errno::Source + ?Sized, E: From<Errno>>(
file: BorrowedFd<'_>,
) -> Result<OwnedFd, E> {
unsafe { OwnedFd::try_adopt::<S, E>(libc::fcntl(file.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0)) }
}
pub(super) fn read<'a, S: errno::Source + ?Sized, E: From<Errno>>(
file: BorrowedFd<'_>,
output: &'a mut [u8],
) -> Result<&'a mut [u8], E> {
unsafe {
let raw = libc::read(file.as_raw_fd(), output.as_mut_ptr().cast(), output.len());
io::raw::Buffer::try_native::<S, E>(output, raw)
}
}
pub(super) fn try_write<'a, S: errno::Source + ?Sized, E: From<Errno>>(
file: BorrowedFd<'_>,
input: &'a [u8],
) -> Result<&'a [u8], E> {
unsafe { io::raw::Buffer::try_native::<S, E>(input, write(file, input)) }
}
pub trait Adopt: fd::FromRawFd + Sized {
unsafe fn try_adopt<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
raw: fd::RawFd,
) -> Result<Self, E> {
let value = unsafe { kernel::raw::Status::new(raw).try_value::<S, E>() }?;
Ok(unsafe { Self::from_raw_fd(value.get()) })
}
}
impl<T: fd::FromRawFd> Adopt for T {}
pub(super) fn flags<
S: errno::Source + ?Sized,
F: super::Flags,
const SET: bool,
const RETRY: bool,
>(
file: BorrowedFd<'_>,
flags: libc::c_int,
) -> Result<libc::c_int, Errno> {
const {
assert!(matches!(
(F::READ, F::WRITE),
(libc::F_GETFD, libc::F_SETFD) | (libc::F_GETFL, libc::F_SETFL)
));
}
loop {
let result = unsafe {
if SET {
let status = libc::fcntl(file.as_raw_fd(), F::WRITE, flags);
kernel::raw::Status::new(status)
.try_zero::<S, Errno>()
.and(Ok(0))
} else {
let status = libc::fcntl(file.as_raw_fd(), F::READ);
kernel::raw::Status::new(status)
.try_value::<S, Errno>()
.map(kernel::Value::get)
}
};
match result {
Err(error) if RETRY && error.is_intr() => continue,
result => return result,
}
}
}
pub(crate) fn write(file: BorrowedFd<'_>, input: &[u8]) -> libc::ssize_t {
unsafe { libc::write(file.as_raw_fd(), input.as_ptr().cast(), input.len()) }
}