Skip to main content

dope_sys/io/file/
raw.rs

1use std::{mem::MaybeUninit, os::fd};
2
3use crate::{Errno, io, kernel};
4use io::file::{self, metadata::Metadata, watch};
5
6/// # Safety
7/// Descriptors stay fixed until owner drop; names retain exclusive storage through borrowing.
8/// Watches retain registration; events borrow only admitted records.
9pub unsafe trait Directory: kernel::raw::Source {
10    type Stream;
11    type Watch;
12    type Events<'a>: Iterator<Item = watch::Event<'a>>;
13
14    /// # Safety
15    /// Bytes contain complete initialized native records for this watch,
16    /// including nonzero event masks.
17    unsafe fn watch_events<'a>(watch: &Self::Watch, bytes: &'a [u8]) -> Self::Events<'a>;
18
19    fn open_dir<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Self::Stream, file::OpenError<E>>
20    where
21        Self: file::File,
22    {
23        let file = Self::open(
24            path,
25            file::Open::DIRECTORY | file::Open::CLOSE_ON_EXEC,
26            file::Mode::new(0),
27        )
28        .map_err(file::OpenError::Syscall)?;
29        Self::from_fd(file)
30    }
31
32    fn from_fd<E: From<Errno>>(file: fd::OwnedFd) -> Result<Self::Stream, file::OpenError<E>>;
33    fn descriptor(stream: &Self::Stream) -> kernel::raw::Descriptor;
34    fn next(stream: &mut Self::Stream) -> Result<Option<file::Entry<'_>>, Errno>;
35}
36
37/// # Safety
38/// Each decoded success retains the uniquely transferred descriptor until
39/// delivery or reclamation.
40pub unsafe trait Completion {
41    type Outcome;
42    type Invalid;
43
44    /// # Safety
45    /// A successful outcome transfers one live descriptor from a completed
46    /// open operation. Its descriptor has not been decoded or reclaimed before.
47    unsafe fn open(outcome: Self::Outcome) -> Result<Result<fd::OwnedFd, Errno>, Self::Invalid>;
48}
49
50pub(super) fn parent(dir: Option<fd::BorrowedFd<'_>>) -> fd::RawFd {
51    dir.as_ref().map_or(libc::AT_FDCWD, fd::AsRawFd::as_raw_fd)
52}
53
54pub(super) unsafe fn metadata<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
55    result: libc::c_int,
56    output: &MaybeUninit<libc::stat>,
57) -> Result<Metadata, E> {
58    // SAFETY: the caller pairs one stat call's unchanged status with its destination.
59    unsafe {
60        io::raw::status::<S, E>(result)?;
61        Ok(Metadata::new(output.assume_init_ref()))
62    }
63}
64
65pub(super) fn unlink_at<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
66    dir: Option<fd::BorrowedFd<'_>>,
67    path: &std::ffi::CStr,
68    flags: libc::c_int,
69) -> Result<(), E> {
70    // SAFETY: unlinkat borrows both inputs and returns zero or -1 with unchanged errno.
71    unsafe { io::raw::status::<S, E>(libc::unlinkat(parent(dir), path.as_ptr(), flags)) }
72}