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, 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 { libc::open(path.as_ptr(), flags.raw(), mode.raw() as libc::c_uint) };
126        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
127    }
128
129    fn metadata<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<Metadata, E> {
130        let mut value = mem::MaybeUninit::uninit();
131        let raw = unsafe { libc::fstat(file.as_raw_fd(), value.as_mut_ptr()) };
132        // SAFETY: fstat returns zero after filling value or -1 on failure.
133        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
134        Ok(Metadata::new(unsafe { value.assume_init() }))
135    }
136
137    fn stat<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Metadata, E> {
138        let mut value = mem::MaybeUninit::uninit();
139        let raw = unsafe { libc::stat(path.as_ptr(), value.as_mut_ptr()) };
140        // SAFETY: stat returns zero after filling value or -1 on failure.
141        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
142        Ok(Metadata::new(unsafe { value.assume_init() }))
143    }
144
145    fn mkdir<E: From<Errno>>(path: &std::ffi::CStr, mode: Mode) -> Result<(), E> {
146        // SAFETY: the terminated path stays borrowed; mkdir returns zero or -1.
147        unsafe {
148            kernel::raw::Status::new(libc::mkdir(path.as_ptr(), mode.raw())).try_zero::<Self, E>()
149        }
150    }
151
152    /// Classifies the named entry itself while retaining its parent directory.
153    fn metadata_at<E: From<Errno>>(
154        dir: Option<BorrowedFd<'_>>,
155        name: &std::ffi::CStr,
156    ) -> Result<Metadata, E> {
157        let mut value = mem::MaybeUninit::uninit();
158        // SAFETY: the parent, name and complete native metadata output stay live.
159        let raw = unsafe {
160            libc::fstatat(
161                dir.map_or(libc::AT_FDCWD, |dir| dir.as_raw_fd()),
162                name.as_ptr(),
163                value.as_mut_ptr(),
164                libc::AT_SYMLINK_NOFOLLOW,
165            )
166        };
167        // SAFETY: fstatat returns zero with initialized metadata or -1 with errno.
168        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
169        Ok(Metadata::new(unsafe { value.assume_init() }))
170    }
171
172    fn unlink<E: From<Errno>>(path: &std::ffi::CStr) -> Result<(), E> {
173        // SAFETY: path is terminated and retained; unlink returns zero or -1.
174        unsafe { kernel::raw::Status::new(libc::unlink(path.as_ptr())).try_zero::<Self, E>() }
175    }
176
177    fn rename<E: From<Errno>>(from: &std::ffi::CStr, to: &std::ffi::CStr) -> Result<(), E> {
178        // SAFETY: both terminated paths remain borrowed; rename returns zero or -1.
179        unsafe {
180            kernel::raw::Status::new(libc::rename(from.as_ptr(), to.as_ptr())).try_zero::<Self, E>()
181        }
182    }
183
184    /// Attempts an exclusive advisory lock without waiting for its current owner.
185    fn try_lock<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<(), E> {
186        // SAFETY: the descriptor remains borrowed; nonblocking flock returns zero or -1.
187        unsafe {
188            kernel::raw::Status::new(libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB))
189                .try_zero::<Self, E>()
190        }
191    }
192
193    fn sync<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<(), E> {
194        // SAFETY: the descriptor remains borrowed; fsync returns zero or -1.
195        unsafe { kernel::raw::Status::new(libc::fsync(file.as_raw_fd())).try_zero::<Self, E>() }
196    }
197
198    fn truncate<E: From<Errno>>(file: BorrowedFd<'_>, len: i64) -> Result<(), E> {
199        // SAFETY: the descriptor remains borrowed; ftruncate returns zero or -1.
200        unsafe {
201            kernel::raw::Status::new(libc::ftruncate(file.as_raw_fd(), len)).try_zero::<Self, E>()
202        }
203    }
204
205    fn unlink_at<E: From<Errno>>(dir: BorrowedFd<'_>, name: &std::ffi::CStr) -> Result<(), E> {
206        // SAFETY: the descriptor and terminated name remain borrowed; unlinkat returns zero or -1.
207        unsafe {
208            kernel::raw::Status::new(libc::unlinkat(dir.as_raw_fd(), name.as_ptr(), 0))
209                .try_zero::<Self, E>()
210        }
211    }
212
213    fn remove_dir_at<E: From<Errno>>(
214        dir: Option<BorrowedFd<'_>>,
215        name: &std::ffi::CStr,
216    ) -> Result<(), E> {
217        // SAFETY: the parent and terminated name remain borrowed; unlinkat removes
218        // only an empty directory and returns zero or -1 with this thread's errno.
219        unsafe {
220            kernel::raw::Status::new(libc::unlinkat(
221                dir.map_or(libc::AT_FDCWD, |dir| dir.as_raw_fd()),
222                name.as_ptr(),
223                libc::AT_REMOVEDIR,
224            ))
225            .try_zero::<Self, E>()
226        }
227    }
228
229    fn open_at<E: From<Errno>>(
230        dir: BorrowedFd<'_>,
231        name: &std::ffi::CStr,
232        flags: Open,
233        mode: Mode,
234    ) -> Result<OwnedFd, E> {
235        let raw = unsafe {
236            libc::openat(
237                dir.as_raw_fd(),
238                name.as_ptr(),
239                flags.raw(),
240                mode.raw() as libc::c_uint,
241            )
242        };
243        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
244    }
245
246    fn rename_at<E: From<Errno>>(
247        dir: BorrowedFd<'_>,
248        old: &std::ffi::CStr,
249        new: &std::ffi::CStr,
250    ) -> Result<(), E> {
251        // SAFETY: the descriptor and terminated names remain borrowed; renameat returns zero or -1.
252        unsafe {
253            kernel::raw::Status::new(libc::renameat(
254                dir.as_raw_fd(),
255                old.as_ptr(),
256                dir.as_raw_fd(),
257                new.as_ptr(),
258            ))
259            .try_zero::<Self, E>()
260        }
261    }
262
263    /// Reads one prefix without changing the descriptor's current position.
264    fn read_at<'a, E: From<Errno>>(
265        file: BorrowedFd<'_>,
266        output: &'a mut [u8],
267        offset: Offset,
268    ) -> Result<&'a mut [u8], E> {
269        // SAFETY: MaybeUninit preserves u8's layout; the exclusive loan is unchanged.
270        let output =
271            unsafe { std::slice::from_raw_parts_mut(output.as_mut_ptr().cast(), output.len()) };
272        raw::read_at::<Self, E>(file, output, offset)
273    }
274
275    fn read_uninit_at<'a, E: From<Errno>>(
276        file: BorrowedFd<'_>,
277        output: &'a mut [mem::MaybeUninit<u8>],
278        offset: Offset,
279    ) -> Result<&'a mut [u8], E> {
280        raw::read_at::<Self, E>(file, output, offset)
281    }
282
283    fn write_at<E: From<Errno>>(
284        file: BorrowedFd<'_>,
285        input: bytes::Prefix<'_, { bounded::MAX }>,
286        offset: Offset,
287    ) -> Result<U32<0, { bounded::MAX as u32 }>, E> {
288        use kernel::raw::Status;
289
290        const { assert!(libc::off_t::MAX as u64 == i64::MAX as u64) };
291        let input = input.as_slice();
292        // SAFETY: the offset's admitted nonnegative range fits the native ABI.
293        let raw = unsafe {
294            libc::pwrite(
295                file.as_raw_fd(),
296                input.as_ptr().cast(),
297                input.len(),
298                offset.get() as libc::off_t,
299            )
300        };
301        // SAFETY: pwrite returns -1 or a count within this Prefix's i32::MAX-bound
302        // input; failure reads the unchanged errno on this thread.
303        Ok(unsafe { Status::from_count(raw).try_count::<Self, E>() }?.bounded())
304    }
305}