Skip to main content

dope_core/io/fs/
mod.rs

1use dope_sys::io::reactor::event::kind;
2use std::{fs, mem, os::fd};
3
4use dope_sys::io::{fd::Fd as _, file, request::Request};
5use file::File as _;
6use o3::{
7    base::marker::ThreadBound,
8    buffer::bytes::{self, bounded},
9};
10
11use crate::{
12    Backend, Errno,
13    driver::route::{self, kind::Class},
14    io::{fs::metadata::Metadata, transfer},
15};
16
17mod dir;
18
19mod len;
20pub mod metadata;
21pub mod open;
22pub mod path;
23pub mod raw;
24
25pub use dir::Dir;
26pub use len::Len;
27
28/// Absolute byte position representable by every file backend.
29#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
30#[repr(transparent)]
31pub struct Offset(file::Offset);
32
33/// Exact position or length outside the absolute file-offset domain.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub struct Overflow {
36    pub actual: u64,
37    pub maximum: u64,
38}
39
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub struct Extent {
42    offset: Offset,
43    length: transfer::Len,
44}
45
46impl From<Len> for Offset {
47    fn from(length: Len) -> Self {
48        Self(length.0)
49    }
50}
51
52impl From<transfer::Len> for Offset {
53    fn from(length: transfer::Len) -> Self {
54        Self(file::Offset::clamp(length.into_raw() as u64))
55    }
56}
57
58impl Offset {
59    pub const fn fixed<const OFFSET: u64>() -> Self {
60        const { assert!(OFFSET <= i64::MAX as u64) };
61        Self(file::Offset::clamp(OFFSET))
62    }
63
64    pub const fn try_new(value: u64) -> Result<Self, Overflow> {
65        match file::Offset::new(value) {
66            Some(value) => Ok(Self(value)),
67            None => Err(Overflow {
68                actual: value,
69                maximum: i64::MAX as u64,
70            }),
71        }
72    }
73
74    pub const fn get(self) -> u64 {
75        self.0.get()
76    }
77
78    pub const fn checked_add(self, length: transfer::Len) -> Result<Self, Extent> {
79        let value = self.get() + length.into_raw() as u64;
80        match Self::try_new(value) {
81            Ok(value) => Ok(value),
82            Err(_) => Err(Extent::new(self, length)),
83        }
84    }
85
86    pub const fn checked_sub(self, length: transfer::Len) -> Result<Self, Extent> {
87        match self.0.checked_sub(length.into_raw() as u64) {
88            Some(value) => Ok(Self(value)),
89            None => Err(Extent::new(self, length)),
90        }
91    }
92}
93
94impl Extent {
95    const fn new(offset: Offset, length: transfer::Len) -> Self {
96        Self { offset, length }
97    }
98}
99
100const _: () = {
101    assert!(mem::size_of::<Offset>() == mem::size_of::<u64>());
102    assert!(mem::align_of::<Offset>() == mem::align_of::<u64>());
103    assert!(mem::size_of::<Extent>() == 2 * mem::size_of::<u64>());
104    assert!(mem::align_of::<Extent>() == mem::align_of::<u64>());
105    assert!(mem::size_of::<Result<Offset, Extent>>() == 3 * mem::size_of::<u64>());
106    assert!(mem::align_of::<Result<Offset, Extent>>() == mem::align_of::<u64>());
107};
108
109/// A native file operation borrowing every descriptor and output it captures.
110///
111/// Raw tokens cannot enter the safe file submission boundary:
112///
113///
114///
115/// Keeping the captured buffer until the submission is dropped is valid.
116pub struct Submission<'a, 'd, Tag, C = <Tag as route::Tag>::Class>
117where
118    Tag: route::Tag,
119    C: Class,
120{
121    raw: <Backend as file::File>::Request<'a>,
122    target: route::Operation<'d, Tag, C>,
123}
124
125impl<'a, 'd, Tag, C> Submission<'a, 'd, Tag, C>
126where
127    Tag: route::Tag,
128    C: Class,
129{
130    fn bind(
131        raw: <Backend as file::File>::Request<'a>,
132        target: route::Operation<'d, Tag, C>,
133    ) -> Self {
134        Self { raw, target }
135    }
136
137    pub(crate) fn into_parts(
138        self,
139    ) -> (
140        <Backend as file::File>::Request<'a>,
141        route::Operation<'d, Tag, C>,
142    ) {
143        (self.raw, self.target)
144    }
145}
146
147impl<'a, 'd, Tag> Submission<'a, 'd, Tag, kind::Write>
148where
149    Tag: route::Tag,
150{
151    #[doc(hidden)]
152    pub fn write_prefix(
153        fd: fd::BorrowedFd<'a>,
154        buffer: &'a [u8],
155        offset: Offset,
156        target: route::Target<'d, Tag>,
157    ) -> Self
158    where
159        Tag: route::Select<kind::Write>,
160    {
161        let input = bytes::Prefix::new(buffer);
162        Self::bind(
163            Request::write(fd, input, offset.0),
164            target.operation::<kind::Write>(),
165        )
166    }
167}
168
169impl<'a, 'd, Tag> Submission<'a, 'd, Tag, kind::Read>
170where
171    Tag: route::Tag,
172{
173    pub fn watch(
174        watch: &'a <Backend as file::raw::Directory>::Watch,
175        output: bounded::Value<&'a mut [mem::MaybeUninit<u8>]>,
176        target: route::Target<'d, Tag>,
177    ) -> Self
178    where
179        Tag: route::Select<kind::Read>,
180    {
181        use file::File;
182
183        Self::bind(
184            <Backend as File>::Request::watch(watch, output),
185            target.operation::<kind::Read>(),
186        )
187    }
188
189    /// Reads one bounded prefix without changing the descriptor's current position.
190    /// A successful completion reports the exact short count; zero is EOF for
191    /// nonempty output. The native file backend may complete during submission.
192    pub fn read_at(
193        fd: fd::BorrowedFd<'a>,
194        output: bounded::Value<&'a mut [mem::MaybeUninit<u8>]>,
195        offset: Offset,
196        target: route::Target<'d, Tag>,
197    ) -> Self
198    where
199        Tag: route::Select<kind::Read>,
200    {
201        Self::bind(
202            Request::read(fd, output, offset.0),
203            target.operation::<kind::Read>(),
204        )
205    }
206}
207
208impl<'a, 'd, Tag> Submission<'a, 'd, Tag, kind::Sync>
209where
210    Tag: route::Tag,
211{
212    pub fn metadata(
213        fd: fd::BorrowedFd<'a>,
214        output: &'a mut <Backend as file::File>::Metadata,
215        target: route::Target<'d, Tag>,
216    ) -> Self
217    where
218        Tag: route::Select<kind::Sync>,
219    {
220        Self::bind(
221            Request::metadata(fd, output),
222            target.operation::<kind::Sync>(),
223        )
224    }
225
226    /// Submit a durability barrier for all writes completed before this operation.
227    pub fn sync(fd: fd::BorrowedFd<'a>, mode: Sync, target: route::Target<'d, Tag>) -> Self
228    where
229        Tag: route::Select<kind::Sync>,
230    {
231        Self::bind(
232            Request::sync(
233                fd,
234                match mode {
235                    Sync::Data => file::Sync::Data,
236                    Sync::All => file::Sync::All,
237                },
238            ),
239            target.operation::<kind::Sync>(),
240        )
241    }
242
243    /// Atomically replaces `new` with `old` within one retained directory.
244    #[doc(hidden)]
245    pub fn rename(rename: path::Rename<'a>, target: route::Target<'d, Tag>) -> Self
246    where
247        Tag: route::Select<kind::Sync>,
248    {
249        Self::bind(
250            Request::rename(
251                fd::AsFd::as_fd(rename.directory()),
252                rename.old(),
253                rename.new_name(),
254            ),
255            target.operation::<kind::Sync>(),
256        )
257    }
258
259    /// Removes one retained directory entry.
260    #[doc(hidden)]
261    pub fn unlink(entry: path::Entry<'a>, target: route::Target<'d, Tag>) -> Self
262    where
263        Tag: route::Select<kind::Sync>,
264    {
265        Self::bind(
266            Request::unlink(fd::AsFd::as_fd(entry.directory()), entry.name()),
267            target.operation::<kind::Sync>(),
268        )
269    }
270}
271
272/// The durability boundary requested for a submitted file sync.
273pub enum Sync {
274    Data,
275    All,
276}
277
278/// One owned file descriptor, including its kernel file offset and locks.
279#[repr(transparent)]
280pub struct File {
281    fd: fd::OwnedFd,
282    thread: ThreadBound,
283}
284
285impl File {
286    pub fn try_read<'a>(&self, bytes: &'a mut [u8]) -> Result<&'a mut [u8], Errno> {
287        Backend::read::<dope_sys::Errno>(fd::AsFd::as_fd(self), bytes)
288    }
289
290    /// Reads one prefix without changing this file's current position.
291    pub fn try_read_at<'a>(
292        &self,
293        bytes: &'a mut [u8],
294        offset: Offset,
295    ) -> Result<&'a mut [u8], Errno> {
296        Backend::read_at::<dope_sys::Errno>(fd::AsFd::as_fd(self), bytes, offset.0)
297    }
298
299    pub fn try_write<'a>(&self, bytes: &'a [u8]) -> Result<&'a [u8], Errno> {
300        Backend::write::<dope_sys::Errno>(fd::AsFd::as_fd(self), bytes)
301    }
302
303    pub fn metadata(&self) -> Result<Metadata, Errno> {
304        Backend::metadata(fd::AsFd::as_fd(self)).map(Metadata::new)
305    }
306
307    /// Attempts an exclusive advisory lock without waiting for its current owner.
308    pub fn try_lock(&self) -> Result<(), Errno> {
309        Backend::try_lock::<dope_sys::Errno>(fd::AsFd::as_fd(self))
310    }
311
312    pub fn try_sync(&self) -> Result<(), Errno> {
313        Backend::sync::<dope_sys::Errno>(fd::AsFd::as_fd(self))
314    }
315}
316
317impl fd::AsFd for File {
318    fn as_fd(&self) -> fd::BorrowedFd<'_> {
319        self.fd.as_fd()
320    }
321}
322
323impl From<fd::OwnedFd> for File {
324    fn from(file: fd::OwnedFd) -> Self {
325        Self {
326            fd: file,
327            thread: ThreadBound::NEW,
328        }
329    }
330}
331
332impl From<fs::File> for File {
333    fn from(file: fs::File) -> Self {
334        Self {
335            fd: file.into(),
336            thread: ThreadBound::NEW,
337        }
338    }
339}
340
341impl From<File> for fs::File {
342    fn from(file: File) -> Self {
343        file.fd.into()
344    }
345}
346
347impl From<File> for fd::OwnedFd {
348    fn from(file: File) -> Self {
349        file.fd
350    }
351}
352
353const _: () = {
354    assert!(size_of::<File>() == size_of::<fd::OwnedFd>());
355    assert!(align_of::<File>() == align_of::<fd::OwnedFd>());
356};