use std::{mem::MaybeUninit, os::fd};
use crate::{Errno, io, kernel};
use io::file::{self, metadata::Metadata, watch};
pub unsafe trait Directory: kernel::raw::Source {
type Stream;
type Watch;
type Events<'a>: Iterator<Item = watch::Event<'a>>;
unsafe fn watch_events<'a>(watch: &Self::Watch, bytes: &'a [u8]) -> Self::Events<'a>;
fn open_dir<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Self::Stream, file::OpenError<E>>
where
Self: file::File,
{
let file = Self::open(
path,
file::Open::DIRECTORY | file::Open::CLOSE_ON_EXEC,
file::Mode::new(0),
)
.map_err(file::OpenError::Syscall)?;
Self::from_fd(file)
}
fn from_fd<E: From<Errno>>(file: fd::OwnedFd) -> Result<Self::Stream, file::OpenError<E>>;
fn descriptor(stream: &Self::Stream) -> kernel::raw::Descriptor;
fn next(stream: &mut Self::Stream) -> Result<Option<file::Entry<'_>>, Errno>;
}
pub unsafe trait Completion {
type Outcome;
type Invalid;
unsafe fn open(outcome: Self::Outcome) -> Result<Result<fd::OwnedFd, Errno>, Self::Invalid>;
}
pub(super) fn parent(dir: Option<fd::BorrowedFd<'_>>) -> fd::RawFd {
dir.as_ref().map_or(libc::AT_FDCWD, fd::AsRawFd::as_raw_fd)
}
pub(super) unsafe fn metadata<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
result: libc::c_int,
output: &MaybeUninit<libc::stat>,
) -> Result<Metadata, E> {
unsafe {
io::raw::status::<S, E>(result)?;
Ok(Metadata::new(output.assume_init_ref()))
}
}
pub(super) fn unlink_at<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
dir: Option<fd::BorrowedFd<'_>>,
path: &std::ffi::CStr,
flags: libc::c_int,
) -> Result<(), E> {
unsafe { io::raw::status::<S, E>(libc::unlinkat(parent(dir), path.as_ptr(), flags)) }
}