1use std::{mem::MaybeUninit, os::fd};
2
3use crate::{Errno, io, kernel};
4use io::file::{self, metadata::Metadata, watch};
5
6pub unsafe trait Directory: kernel::raw::Source {
10 type Stream;
11 type Watch;
12 type Events<'a>: Iterator<Item = watch::Event<'a>>;
13
14 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
37pub unsafe trait Completion {
41 type Outcome;
42 type Invalid;
43
44 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 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 unsafe { io::raw::status::<S, E>(libc::unlinkat(parent(dir), path.as_ptr(), flags)) }
72}