dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::{mem::MaybeUninit, os::fd};

use crate::{Errno, io, kernel};
use io::file::{self, metadata::Metadata, watch};

/// # Safety
/// Descriptors stay fixed until owner drop; names retain exclusive storage through borrowing.
/// Watches retain registration; events borrow only admitted records.
pub unsafe trait Directory: kernel::raw::Source {
    type Stream;
    type Watch;
    type Events<'a>: Iterator<Item = watch::Event<'a>>;

    /// # Safety
    /// Bytes contain complete initialized native records for this watch,
    /// including nonzero event masks.
    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>;
}

/// # Safety
/// Each decoded success retains the uniquely transferred descriptor until
/// delivery or reclamation.
pub unsafe trait Completion {
    type Outcome;
    type Invalid;

    /// # Safety
    /// A successful outcome transfers one live descriptor from a completed
    /// open operation. Its descriptor has not been decoded or reclaimed before.
    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> {
    // SAFETY: the caller pairs one stat call's unchanged status with its destination.
    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> {
    // SAFETY: unlinkat borrows both inputs and returns zero or -1 with unchanged errno.
    unsafe { io::raw::status::<S, E>(libc::unlinkat(parent(dir), path.as_ptr(), flags)) }
}