Skip to main content

dope_sys/io/file/
mod.rs

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