Skip to main content

dope_core/io/fs/
mod.rs

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