Skip to main content

hyprstream_containedfs/
types.rs

1//! Core types for contained filesystem operations.
2
3use crate::error::FsError;
4use std::fs::{self, File, OpenOptions};
5use std::path::PathBuf;
6
7// ─────────────────────────────────────────────────────────────────────────────
8// OpenMode — bitflags for 9P-style open modes
9// ─────────────────────────────────────────────────────────────────────────────
10
11bitflags::bitflags! {
12    /// Open mode flags (9P-aligned).
13    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
14    pub struct OpenMode: u8 {
15        /// Open for reading.
16        const OREAD   = 0x00;
17        /// Open for writing.
18        const OWRITE  = 0x01;
19        /// Open for read+write.
20        const ORDWR   = 0x02;
21        /// Truncate file on open.
22        const OTRUNC  = 0x10;
23        /// Append mode.
24        const OAPPEND = 0x20;
25        /// Exclusive creation (fail if exists).
26        const OEXCL   = 0x40;
27    }
28}
29
30impl OpenMode {
31    /// Check if write access is requested.
32    pub fn is_write(&self) -> bool {
33        self.contains(Self::OWRITE) || self.contains(Self::ORDWR)
34    }
35
36    /// Check if truncation is requested.
37    pub fn is_truncate(&self) -> bool {
38        self.contains(Self::OTRUNC)
39    }
40
41    /// Check if append is requested.
42    pub fn is_append(&self) -> bool {
43        self.contains(Self::OAPPEND)
44    }
45
46    /// Check if exclusive creation is requested.
47    pub fn is_exclusive(&self) -> bool {
48        self.contains(Self::OEXCL)
49    }
50
51    /// Convert to `std::fs::OpenOptions`.
52    pub fn to_open_options(&self) -> OpenOptions {
53        let mut opts = OpenOptions::new();
54        opts.read(true);
55        if self.is_write() {
56            opts.write(true);
57        }
58        if self.is_truncate() {
59            opts.truncate(true);
60        }
61        if self.is_append() {
62            opts.append(true);
63        }
64        opts
65    }
66
67    /// Convert to `std::fs::OpenOptions` with create enabled.
68    pub fn to_create_options(&self) -> OpenOptions {
69        let mut opts = self.to_open_options();
70        if self.is_exclusive() {
71            opts.create_new(true);
72        } else {
73            opts.create(true);
74        }
75        opts
76    }
77}
78
79// ─────────────────────────────────────────────────────────────────────────────
80// FsHandle — opaque handle from walk operations
81// ─────────────────────────────────────────────────────────────────────────────
82
83/// Handle returned by `walk()` for 9P walk state.
84///
85/// Opaque struct with platform-specific internals.
86/// On Linux: wraps a pathrs::Handle (O_PATH fd from openat2).
87/// On non-Linux: wraps a validated PathBuf.
88pub struct FsHandle {
89    rel_path: String,
90    inner: FsHandleInner,
91}
92
93enum FsHandleInner {
94    #[cfg(target_os = "linux")]
95    Pathrs(pathrs::Handle),
96    Path(PathBuf),
97}
98
99impl FsHandle {
100    /// Create a handle from a pathrs Handle (Linux).
101    #[cfg(target_os = "linux")]
102    pub(crate) fn from_pathrs(handle: pathrs::Handle, rel_path: String) -> Self {
103        Self {
104            rel_path,
105            inner: FsHandleInner::Pathrs(handle),
106        }
107    }
108
109    /// Create a handle from a validated PathBuf.
110    pub(crate) fn from_path(path: PathBuf, rel_path: String) -> Self {
111        Self {
112            rel_path,
113            inner: FsHandleInner::Path(path),
114        }
115    }
116
117    /// Get the relative path from the contained root to this handle.
118    pub fn rel_path(&self) -> &str {
119        &self.rel_path
120    }
121
122    /// Compute the relative path for a child entry under this directory.
123    ///
124    /// Returns `name` if this handle is at the root (`.` or empty),
125    /// otherwise returns `"{rel_path}/{name}"`.
126    pub fn child_rel_path(&self, name: &str) -> String {
127        let parent = self.rel_path();
128        if parent == "." || parent.is_empty() {
129            name.to_owned()
130        } else {
131            format!("{}/{}", parent, name)
132        }
133    }
134
135    /// Get file metadata from this handle.
136    pub fn metadata(&self) -> Result<fs::Metadata, FsError> {
137        match &self.inner {
138            #[cfg(target_os = "linux")]
139            FsHandleInner::Pathrs(handle) => {
140                use pathrs::flags::OpenFlags;
141                let file: File = handle
142                    .reopen(OpenFlags::O_RDONLY | OpenFlags::O_CLOEXEC)
143                    .map_err(|e| FsError::Io(std::io::Error::other(e.to_string())))?;
144                file.metadata().map_err(FsError::Io)
145            }
146            FsHandleInner::Path(path) => fs::metadata(path).map_err(FsError::Io),
147        }
148    }
149
150    /// Open this handle as a real file for I/O.
151    pub fn open_file(&self, write: bool) -> Result<File, FsError> {
152        match &self.inner {
153            #[cfg(target_os = "linux")]
154            FsHandleInner::Pathrs(handle) => {
155                use pathrs::flags::OpenFlags;
156                let mut flags = OpenFlags::O_CLOEXEC;
157                if write {
158                    flags |= OpenFlags::O_RDWR;
159                } else {
160                    flags |= OpenFlags::O_RDONLY;
161                }
162                handle
163                    .reopen(flags)
164                    .map_err(|e| FsError::Io(std::io::Error::other(e.to_string())))
165            }
166            FsHandleInner::Path(path) => {
167                let mut opts = OpenOptions::new();
168                opts.read(true);
169                if write {
170                    opts.write(true);
171                }
172                opts.open(path).map_err(FsError::Io)
173            }
174        }
175    }
176}
177
178impl std::fmt::Debug for FsHandle {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        f.debug_struct("FsHandle")
181            .field("rel_path", &self.rel_path)
182            .finish()
183    }
184}
185
186// ─────────────────────────────────────────────────────────────────────────────
187// Stat — filesystem metadata
188// ─────────────────────────────────────────────────────────────────────────────
189
190/// Filesystem metadata returned by `stat()`.
191#[derive(Debug, Clone)]
192pub struct Stat {
193    /// QID type (QTDIR for directories, QTFILE for files).
194    pub qtype: u8,
195    /// File mode/permissions.
196    pub mode: u32,
197    /// Access time (Unix timestamp).
198    pub atime: u64,
199    /// Modification time (Unix timestamp).
200    pub mtime: u64,
201    /// File size in bytes.
202    pub length: u64,
203    /// File name.
204    pub name: String,
205}
206
207/// QID type constant for directories.
208pub const QTDIR: u8 = 0x80;
209/// QID type constant for regular files.
210pub const QTFILE: u8 = 0x00;
211
212impl Stat {
213    /// Create a Stat from `std::fs::Metadata` and a name.
214    pub fn from_metadata(meta: &fs::Metadata, name: String) -> Self {
215        use std::time::UNIX_EPOCH;
216
217        let qtype = if meta.is_dir() { QTDIR } else { QTFILE };
218        let atime = meta
219            .accessed()
220            .ok()
221            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
222            .map(|d| d.as_secs())
223            .unwrap_or(0);
224        let mtime = meta
225            .modified()
226            .ok()
227            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
228            .map(|d| d.as_secs())
229            .unwrap_or(0);
230
231        #[cfg(unix)]
232        let mode = {
233            use std::os::unix::fs::PermissionsExt;
234            meta.permissions().mode()
235        };
236        #[cfg(not(unix))]
237        let mode = if meta.is_dir() { 0o755 } else { 0o644 };
238
239        Self {
240            qtype,
241            mode,
242            atime,
243            mtime,
244            length: meta.len(),
245            name,
246        }
247    }
248}
249
250// ─────────────────────────────────────────────────────────────────────────────
251// DirEntry — directory listing entry
252// ─────────────────────────────────────────────────────────────────────────────
253
254/// Directory entry returned by `readdir()`.
255#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
256pub struct DirEntry {
257    /// Entry name.
258    pub name: String,
259    /// Whether this entry is a directory.
260    pub is_dir: bool,
261    /// File size in bytes.
262    pub size: u64,
263}