Skip to main content

dope_sys/io/file/
mod.rs

1use std::{
2    mem,
3    os::fd::{AsRawFd as _, BorrowedFd, OwnedFd},
4};
5
6use o3::{
7    alloc,
8    base::num::bounded::{U32, U64},
9    buffer::bytes::{self, bounded},
10};
11pub use sync::Sync;
12
13use crate::{
14    Errno,
15    io::{fd, request::Request},
16    kernel::{self, errno},
17};
18
19mod kind;
20mod metadata;
21mod mode;
22mod open;
23pub mod raw;
24mod sync;
25pub mod watch;
26
27pub use kind::Kind;
28pub use metadata::{Error as MetadataError, Identity, Metadata, Owner, Value as MetadataValue};
29pub use mode::Mode;
30pub use open::Open;
31
32/// An absolute file position, excluding native current-position sentinels.
33#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
34#[repr(transparent)]
35pub struct Offset(U64<0, { i64::MAX as u64 }>);
36
37impl Offset {
38    pub const fn new(value: u64) -> Option<Self> {
39        match U64::new(value) {
40            Some(value) => Some(Self(value)),
41            None => None,
42        }
43    }
44
45    pub const fn clamp(value: u64) -> Self {
46        Self(U64::clamp(value))
47    }
48
49    pub const fn get(self) -> u64 {
50        self.0.get()
51    }
52
53    /// Subtracts a byte count while retaining the admitted absolute range.
54    pub const fn checked_sub(self, value: u64) -> Option<Self> {
55        match self.0.checked_sub(value) {
56            Some(value) => Some(Self(value)),
57            None => None,
58        }
59    }
60}
61
62/// A decoded file completion retaining any descriptor it owns.
63pub type Opened = Result<OwnedFd, Errno>;
64
65/// A native directory stream whose descriptor and buffered entries have one owner.
66#[repr(transparent)]
67pub struct Dir<S: raw::Directory>(S::Stream);
68
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum OpenError<E> {
71    Syscall(E),
72    Allocation(alloc::Exhausted),
73}
74
75impl<S: File> Dir<S> {
76    pub fn open<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Self, OpenError<E>> {
77        S::open_dir(path).map(Self)
78    }
79
80    pub fn from_fd<E: From<Errno>>(file: OwnedFd) -> Result<Self, OpenError<E>> {
81        S::from_fd(file).map(Self)
82    }
83
84    pub fn entries(&mut self) -> (BorrowedFd<'_>, Entries<'_, S>) {
85        let file = S::descriptor(&self.0);
86        (
87            // SAFETY: Directory preserves this descriptor until the stream is dropped,
88            // and its mutable borrow excludes dropping the owner for both returned borrows.
89            unsafe { BorrowedFd::borrow_raw(file.get()) },
90            Entries(&mut self.0),
91        )
92    }
93}
94
95#[repr(transparent)]
96pub struct Entries<'a, S: raw::Directory>(&'a mut S::Stream);
97
98/// One name and the file kind already supplied by its native directory record.
99#[derive(Clone, Copy, Debug)]
100pub struct Entry<'a> {
101    pub name: &'a std::ffi::CStr,
102    pub kind: Option<Kind>,
103}
104
105impl<S: raw::Directory> Entries<'_, S> {
106    /// The next read requires the previous name's borrow to end.
107    pub fn try_next(&mut self) -> Result<Option<Entry<'_>>, Errno> {
108        S::next(self.0)
109    }
110}
111
112/// Selects native file requests while preserving every caller-owned borrow.
113pub trait File: errno::Source + raw::Directory {
114    type Options;
115    type Metadata;
116    type Request<'a>: Request<
117            'a,
118            Options = Self::Options,
119            Metadata = Self::Metadata,
120            Buffer = bytes::Prefix<'a, { bounded::MAX }>,
121        >
122    where
123        Self: 'a;
124    fn open<E: From<Errno>>(path: &std::ffi::CStr, flags: Open, mode: Mode) -> Result<OwnedFd, E> {
125        let raw = unsafe {
126            libc::open(
127                path.as_ptr(),
128                flags.raw(),
129                mode.raw() as libc::mode_t as libc::c_uint,
130            )
131        };
132        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
133    }
134
135    fn metadata<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<Metadata, E> {
136        let mut value = mem::MaybeUninit::uninit();
137        let raw = unsafe { libc::fstat(file.as_raw_fd(), value.as_mut_ptr()) };
138        // SAFETY: fstat returns zero after filling value or -1 on failure.
139        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
140        Ok(Metadata::new(unsafe { value.assume_init() }))
141    }
142
143    fn stat<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Metadata, E> {
144        let mut value = mem::MaybeUninit::uninit();
145        let raw = unsafe { libc::stat(path.as_ptr(), value.as_mut_ptr()) };
146        // SAFETY: stat returns zero after filling value or -1 on failure.
147        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
148        Ok(Metadata::new(unsafe { value.assume_init() }))
149    }
150
151    fn set_owner<E: From<Errno>>(file: BorrowedFd<'_>, owner: Owner) -> Result<(), E> {
152        // SAFETY: the descriptor remains borrowed; fchown returns zero or -1.
153        unsafe {
154            kernel::raw::Status::new(libc::fchown(file.as_raw_fd(), owner.uid, owner.gid))
155                .try_zero::<Self, E>()
156        }
157    }
158
159    fn set_permissions<E: From<Errno>>(file: BorrowedFd<'_>, mode: Mode) -> Result<(), E> {
160        // SAFETY: the descriptor remains borrowed; fchmod returns zero or -1.
161        unsafe {
162            kernel::raw::Status::new(libc::fchmod(file.as_raw_fd(), mode.raw() as libc::mode_t))
163                .try_zero::<Self, E>()
164        }
165    }
166
167    fn mkdir<E: From<Errno>>(path: &std::ffi::CStr, mode: Mode) -> Result<(), E> {
168        // SAFETY: the terminated path stays borrowed; mkdir returns zero or -1.
169        unsafe {
170            kernel::raw::Status::new(libc::mkdir(path.as_ptr(), mode.raw() as libc::mode_t))
171                .try_zero::<Self, E>()
172        }
173    }
174
175    /// Classifies the named entry itself while retaining its parent directory.
176    fn metadata_at<E: From<Errno>>(
177        dir: Option<BorrowedFd<'_>>,
178        name: &std::ffi::CStr,
179    ) -> Result<Metadata, E> {
180        let mut value = mem::MaybeUninit::uninit();
181        // SAFETY: the parent, name and complete native metadata output stay live.
182        let raw = unsafe {
183            libc::fstatat(
184                dir.map_or(libc::AT_FDCWD, |dir| dir.as_raw_fd()),
185                name.as_ptr(),
186                value.as_mut_ptr(),
187                libc::AT_SYMLINK_NOFOLLOW,
188            )
189        };
190        // SAFETY: fstatat returns zero with initialized metadata or -1 with errno.
191        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
192        Ok(Metadata::new(unsafe { value.assume_init() }))
193    }
194
195    fn unlink<E: From<Errno>>(path: &std::ffi::CStr) -> Result<(), E> {
196        // SAFETY: path is terminated and retained; unlink returns zero or -1.
197        unsafe { kernel::raw::Status::new(libc::unlink(path.as_ptr())).try_zero::<Self, E>() }
198    }
199
200    fn rename<E: From<Errno>>(from: &std::ffi::CStr, to: &std::ffi::CStr) -> Result<(), E> {
201        // SAFETY: both terminated paths remain borrowed; rename returns zero or -1.
202        unsafe {
203            kernel::raw::Status::new(libc::rename(from.as_ptr(), to.as_ptr())).try_zero::<Self, E>()
204        }
205    }
206
207    /// Attempts an exclusive advisory lock without waiting for its current owner.
208    fn try_lock<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<(), E> {
209        // SAFETY: the descriptor remains borrowed; nonblocking flock returns zero or -1.
210        unsafe {
211            kernel::raw::Status::new(libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB))
212                .try_zero::<Self, E>()
213        }
214    }
215
216    fn sync<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<(), E> {
217        // SAFETY: the descriptor remains borrowed; fsync returns zero or -1.
218        unsafe { kernel::raw::Status::new(libc::fsync(file.as_raw_fd())).try_zero::<Self, E>() }
219    }
220
221    fn truncate<E: From<Errno>>(file: BorrowedFd<'_>, len: i64) -> Result<(), E> {
222        // SAFETY: the descriptor remains borrowed; ftruncate returns zero or -1.
223        unsafe {
224            kernel::raw::Status::new(libc::ftruncate(file.as_raw_fd(), len)).try_zero::<Self, E>()
225        }
226    }
227
228    fn unlink_at<E: From<Errno>>(dir: BorrowedFd<'_>, name: &std::ffi::CStr) -> Result<(), E> {
229        // SAFETY: the descriptor and terminated name remain borrowed; unlinkat returns zero or -1.
230        unsafe {
231            kernel::raw::Status::new(libc::unlinkat(dir.as_raw_fd(), name.as_ptr(), 0))
232                .try_zero::<Self, E>()
233        }
234    }
235
236    fn remove_dir_at<E: From<Errno>>(
237        dir: Option<BorrowedFd<'_>>,
238        name: &std::ffi::CStr,
239    ) -> Result<(), E> {
240        // SAFETY: the parent and terminated name remain borrowed; unlinkat removes
241        // only an empty directory and returns zero or -1 with this thread's errno.
242        unsafe {
243            kernel::raw::Status::new(libc::unlinkat(
244                dir.map_or(libc::AT_FDCWD, |dir| dir.as_raw_fd()),
245                name.as_ptr(),
246                libc::AT_REMOVEDIR,
247            ))
248            .try_zero::<Self, E>()
249        }
250    }
251
252    fn open_at<E: From<Errno>>(
253        dir: BorrowedFd<'_>,
254        name: &std::ffi::CStr,
255        flags: Open,
256        mode: Mode,
257    ) -> Result<OwnedFd, E> {
258        let raw = unsafe {
259            libc::openat(
260                dir.as_raw_fd(),
261                name.as_ptr(),
262                flags.raw(),
263                mode.raw() as libc::mode_t as libc::c_uint,
264            )
265        };
266        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
267    }
268
269    fn rename_at<E: From<Errno>>(
270        dir: BorrowedFd<'_>,
271        old: &std::ffi::CStr,
272        new: &std::ffi::CStr,
273    ) -> Result<(), E> {
274        // SAFETY: the descriptor and terminated names remain borrowed; renameat returns zero or -1.
275        unsafe {
276            kernel::raw::Status::new(libc::renameat(
277                dir.as_raw_fd(),
278                old.as_ptr(),
279                dir.as_raw_fd(),
280                new.as_ptr(),
281            ))
282            .try_zero::<Self, E>()
283        }
284    }
285
286    /// Reads one prefix without changing the descriptor's current position.
287    fn read_at<'a, E: From<Errno>>(
288        file: BorrowedFd<'_>,
289        output: &'a mut [u8],
290        offset: Offset,
291    ) -> Result<&'a mut [u8], E> {
292        // SAFETY: MaybeUninit preserves u8's layout; the exclusive loan is unchanged.
293        let output =
294            unsafe { std::slice::from_raw_parts_mut(output.as_mut_ptr().cast(), output.len()) };
295        raw::read_at::<Self, E>(file, output, offset)
296    }
297
298    fn read_uninit_at<'a, E: From<Errno>>(
299        file: BorrowedFd<'_>,
300        output: &'a mut [mem::MaybeUninit<u8>],
301        offset: Offset,
302    ) -> Result<&'a mut [u8], E> {
303        raw::read_at::<Self, E>(file, output, offset)
304    }
305
306    fn write_at<E: From<Errno>>(
307        file: BorrowedFd<'_>,
308        input: bytes::Prefix<'_, { bounded::MAX }>,
309        offset: Offset,
310    ) -> Result<U32<0, { bounded::MAX as u32 }>, E> {
311        use kernel::raw::Status;
312
313        const { assert!(libc::off_t::MAX as u64 == i64::MAX as u64) };
314        let input = input.as_slice();
315        // SAFETY: the offset's admitted nonnegative range fits the native ABI.
316        let raw = unsafe {
317            libc::pwrite(
318                file.as_raw_fd(),
319                input.as_ptr().cast(),
320                input.len(),
321                offset.get() as libc::off_t,
322            )
323        };
324        // SAFETY: pwrite returns -1 or a count within this Prefix's i32::MAX-bound
325        // input; failure reads the unchanged errno on this thread.
326        Ok(unsafe { Status::from_count(raw).try_count::<Self, E>() }?.bounded())
327    }
328}