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