Skip to main content

file_system/fundamentals/path/
path_reference.rs

1use core::borrow::Borrow;
2
3use alloc::{borrow::ToOwned, format, string::ToString};
4
5use super::*;
6
7/// A borrowed path type.
8/// The implementation is very similar to the standard library's `std::path::Path`.
9/// However, this implementation is more lightweight and allows for std-less usage.
10#[derive(Debug, PartialEq, Eq, Hash)]
11#[repr(transparent)]
12pub struct Path(str);
13
14impl Path {
15    pub const ROOT: &'static Path = Self::from_str("/");
16    pub const EMPTY: &'static Path = Self::from_str("");
17
18    /// Operating-system code and account records.
19    pub const SYSTEM: &'static Path = Self::from_str("/system");
20    pub const SYSTEM_ACCOUNTS: &'static Path = Self::from_str("/system/accounts");
21    pub const SYSTEM_ACCOUNT_USERS: &'static Path = Self::from_str("/system/accounts/users");
22    pub const SYSTEM_ACCOUNT_GROUPS: &'static Path = Self::from_str("/system/accounts/groups");
23    pub const SYSTEM_EXECUTABLES: &'static Path = Self::from_str("/system/executables");
24    pub const SYSTEM_LIBRARIES: &'static Path = Self::from_str("/system/libraries");
25    pub const SYSTEM_SERVICES: &'static Path = Self::from_str("/system/services");
26
27    /// Runtime device endpoints grouped by function.
28    pub const DEVICES: &'static Path = Self::from_str("/devices");
29    pub const NETWORK_DEVICES: &'static Path = Self::from_str("/devices/network");
30    pub const BLUETOOTH_DEVICES: &'static Path = Self::from_str("/devices/bluetooth");
31    pub const AUDIO_DEVICES: &'static Path = Self::from_str("/devices/audio");
32    pub const COMPUTE_DEVICES: &'static Path = Self::from_str("/devices/compute");
33    pub const GRAPHICS_DEVICES: &'static Path = Self::from_str("/devices/graphics");
34    pub const INPUT_DEVICES: &'static Path = Self::from_str("/devices/input");
35    pub const RANDOM_DEVICES: &'static Path = Self::from_str("/devices/random");
36    pub const STANDARD_IO_DEVICES: &'static Path = Self::from_str("/devices/standard_io");
37    pub const STORAGE_DEVICES: &'static Path = Self::from_str("/devices/storage");
38    pub const TIME_DEVICES: &'static Path = Self::from_str("/devices/time");
39    /// Peripheral device nodes: `/devices/<class>/<name>`, e.g. `/devices/uart/uart0`.
40    pub const UART_DEVICES: &'static Path = Self::from_str("/devices/uart");
41    pub const I2C_DEVICES: &'static Path = Self::from_str("/devices/i2c");
42    pub const SPI_DEVICES: &'static Path = Self::from_str("/devices/spi");
43    pub const ADC_DEVICES: &'static Path = Self::from_str("/devices/adc");
44    pub const GPIO_DEVICES: &'static Path = Self::from_str("/devices/gpio");
45    pub const PWM_DEVICES: &'static Path = Self::from_str("/devices/pwm");
46    pub const HUMAN_INTERFACE_DEVICES: &'static Path = Self::from_str("/devices/human_interface");
47    /// Real-time clock node holding wall-clock time (UTC) across resets.
48    pub const REAL_TIME_CLOCK: &'static Path = Self::from_str("/devices/time/real_time_clock");
49
50    /// System and application configuration.
51    pub const CONFIGURATION: &'static Path = Self::from_str("/configuration");
52    pub const SYSTEM_CONFIGURATION: &'static Path = Self::from_str("/configuration/system");
53    /// Package installation policy, such as the trusted repository key.
54    pub const PACKAGE_CONFIGURATION: &'static Path =
55        Self::from_str("/configuration/system/packages");
56    pub const APPLICATION_CONFIGURATION: &'static Path =
57        Self::from_str("/configuration/applications");
58    pub const SHARED_CONFIGURATION: &'static Path = Self::from_str("/configuration/shared");
59
60    /// Installed application code.
61    pub const APPLICATIONS: &'static Path = Self::from_str("/applications");
62    pub const APPLICATION_EXECUTABLES: &'static Path = Self::from_str("/applications/executables");
63    pub const APPLICATION_LIBRARIES: &'static Path = Self::from_str("/applications/libraries");
64    /// Installed self-contained application bundles: `/applications/bundles/<package-id>/`,
65    /// each the extracted `.xpk` archive (`.xila/`, `executables/`, resources, `shortcut.json`).
66    pub const APPLICATION_BUNDLES: &'static Path = Self::from_str("/applications/bundles");
67
68    /// Mutable persistent state.
69    pub const DATA: &'static Path = Self::from_str("/data");
70    pub const SYSTEM_DATA: &'static Path = Self::from_str("/data/system");
71    pub const SYSTEM_CRASHES: &'static Path = Self::from_str("/system/crashes");
72    pub const SYSTEM_LOGS: &'static Path = Self::from_str("/data/system/logs");
73    pub const APPLICATION_DATA: &'static Path = Self::from_str("/data/applications");
74    pub const SHARED_DATA: &'static Path = Self::from_str("/data/shared");
75
76    /// User homes.
77    pub const USERS: &'static Path = Self::from_str("/users");
78
79    /// Scratch storage cleared at boot.
80    pub const TEMPORARY: &'static Path = Self::from_str("/temporary");
81    pub const TEMPORARY_CACHE: &'static Path = Self::from_str("/temporary/cache");
82    pub const TEMPORARY_SESSIONS: &'static Path = Self::from_str("/temporary/sessions");
83
84    /// # Safety
85    /// The caller must ensure that the string is a valid path string.
86    pub const fn from_str(path: &str) -> &Path {
87        unsafe { &*(path as *const str as *const Path) }
88    }
89
90    /// # Safety
91    /// The caller must ensure that the string is a valid path string.
92    pub fn new<S: AsRef<str> + ?Sized>(path: &S) -> &Path {
93        unsafe { &*(path.as_ref() as *const str as *const Path) }
94    }
95
96    pub fn is_valid(&self) -> bool {
97        is_valid_string(&self.0)
98    }
99
100    pub fn is_absolute(&self) -> bool {
101        self.0.starts_with('/')
102    }
103
104    pub fn is_root(&self) -> bool {
105        &self.0 == "/"
106    }
107
108    pub fn is_empty(&self) -> bool {
109        self.0.is_empty()
110    }
111
112    pub fn is_canonical(&self) -> bool {
113        self.0.chars().all(|c| c != '.')
114    }
115
116    pub fn go_parent(&self) -> Option<&Path> {
117        let characters_to_remove = match self.0.rfind(SEPARATOR) {
118            Some(index) => index,
119            None => {
120                // If there is no separator, the path is either empty or relative to the current directory.
121                if self.get_length() > 0 {
122                    // Relative to the current directory.
123                    return Some(Self::EMPTY);
124                } else {
125                    return None;
126                }
127            }
128        };
129
130        if characters_to_remove == 0 {
131            if self.get_length() == 1 {
132                return None;
133            }
134
135            if self.is_absolute() {
136                return Some(Self::ROOT);
137            } else {
138                return Some(Self::from_str(""));
139            }
140        }
141
142        Some(Self::from_str(&self.0[..characters_to_remove]))
143    }
144
145    pub fn get_file_prefix(&self) -> Option<&str> {
146        let extension_start = self
147            .0
148            .rfind(EXTENSION_SEPARATOR)
149            .or_else(|| Some(self.get_length()))?; // Find the extension separator.
150        let file_prefix_start = self.0.rfind(SEPARATOR).map(|i| i + 1).unwrap_or(0); // Find the file prefix start.
151
152        if extension_start <= file_prefix_start {
153            return None;
154        }
155
156        Some(&self.0[file_prefix_start..extension_start])
157    }
158
159    pub fn get_file_name(&self) -> Option<&str> {
160        let file_prefix_start = self.0.rfind(SEPARATOR).map(|i| i + 1).unwrap_or(0); // Find the file prefix start.
161
162        if file_prefix_start >= self.get_length() {
163            return None;
164        }
165
166        Some(&self.0[file_prefix_start..])
167    }
168
169    pub fn get_extension(&self) -> Option<&str> {
170        let extension_start = self.0.rfind(EXTENSION_SEPARATOR)?;
171
172        Some(&self.0[extension_start + 1..])
173    }
174
175    pub fn set_extension(&self, extension: &str) -> Option<PathOwned> {
176        let extension_start = self
177            .0
178            .rfind(EXTENSION_SEPARATOR)
179            .unwrap_or(self.get_length());
180
181        Some(unsafe {
182            PathOwned::new_unchecked(format!("{}{}", &self.0[..extension_start], extension))
183        })
184    }
185
186    pub fn strip_prefix<'b>(&'b self, path_prefix: &Path) -> Option<&'b Path> {
187        let mut stripped_prefix = self.0.strip_prefix(&path_prefix.0)?;
188
189        if stripped_prefix.starts_with(SEPARATOR) {
190            stripped_prefix = &stripped_prefix[1..]
191        }
192
193        Some(Self::from_str(stripped_prefix))
194    }
195
196    pub fn strip_prefix_absolute<'b>(&'b self, path_prefix: &Path) -> Option<&'b Path> {
197        if path_prefix.is_root() {
198            return Some(self);
199        }
200
201        let stripped_prefix = self.0.strip_prefix(&path_prefix.0)?;
202
203        if stripped_prefix.is_empty() {
204            return Some(Self::ROOT);
205        }
206
207        Some(Self::from_str(stripped_prefix))
208    }
209
210    pub fn strip_suffix<'b>(&'b self, path_suffix: &Path) -> Option<&'b Path> {
211        let stripped_suffix = self.0.strip_suffix(&path_suffix.0)?;
212
213        if stripped_suffix.ends_with(SEPARATOR) {
214            return Some(Self::from_str(
215                &stripped_suffix[..stripped_suffix.len() - 1],
216            ));
217        }
218
219        Some(Self::from_str(stripped_suffix))
220    }
221
222    pub fn get_components(&'_ self) -> Components<'_> {
223        Components::new(self)
224    }
225
226    pub fn join(&self, path: impl AsRef<Path>) -> Option<PathOwned> {
227        self.to_owned().join(path)
228    }
229
230    pub fn append(&self, path: &str) -> Option<PathOwned> {
231        self.to_owned().append(path)
232    }
233
234    pub fn get_length(&self) -> usize {
235        self.0.len()
236    }
237
238    pub fn as_str(&self) -> &str {
239        &self.0
240    }
241}
242
243#[cfg(feature = "std")]
244impl AsRef<std::path::Path> for Path {
245    fn as_ref(&self) -> &std::path::Path {
246        std::path::Path::new(&self.0)
247    }
248}
249
250impl ToOwned for Path {
251    type Owned = PathOwned;
252
253    fn to_owned(&self) -> Self::Owned {
254        unsafe { PathOwned::new_unchecked(self.0.to_string()) }
255    }
256
257    fn clone_into(&self, target: &mut Self::Owned) {
258        *target = self.to_owned();
259    }
260}
261
262impl Borrow<Path> for PathOwned {
263    fn borrow(&self) -> &Path {
264        Path::from_str(&self.0)
265    }
266}
267
268impl AsRef<Path> for str {
269    fn as_ref(&self) -> &Path {
270        Path::from_str(self)
271    }
272}
273
274impl AsRef<str> for &Path {
275    fn as_ref(&self) -> &str {
276        &self.0
277    }
278}
279
280impl AsRef<Path> for Path {
281    fn as_ref(&self) -> &Path {
282        self
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn test_strip_prefix() {
292        let path = Path::from_str("/home/user/file.txt");
293        let prefix = Path::from_str("/home/user");
294        assert_eq!(path.strip_prefix(prefix).unwrap().as_str(), "file.txt");
295
296        let path = Path::from_str("/home/user/file.txt");
297        let prefix = Path::from_str("/");
298        assert_eq!(
299            path.strip_prefix(prefix).unwrap().as_str(),
300            "home/user/file.txt"
301        );
302
303        let invalid_prefix = Path::from_str("/home/invalid/");
304        assert_eq!(path.strip_prefix(invalid_prefix), None);
305    }
306
307    #[test]
308    fn test_strip_prefix_absolute() {
309        let path = Path::from_str("/");
310        let prefix = Path::from_str("/");
311        assert_eq!(path.strip_prefix_absolute(prefix).unwrap().as_str(), "/");
312
313        let path = Path::from_str("/Foo/Bar");
314        let prefix = Path::from_str("/Foo/Bar");
315        assert_eq!(path.strip_prefix_absolute(prefix).unwrap().as_str(), "/");
316
317        let path = Path::from_str("/home/user/file.txt");
318        let prefix = Path::from_str("/home/user");
319        assert_eq!(
320            path.strip_prefix_absolute(prefix).unwrap().as_str(),
321            "/file.txt"
322        );
323
324        let path = Path::from_str("/home/user/file.txt");
325        let prefix = Path::from_str("/");
326        assert_eq!(
327            path.strip_prefix_absolute(prefix).unwrap().as_str(),
328            "/home/user/file.txt"
329        );
330
331        let invalid_prefix = Path::from_str("/home/invalid/");
332        assert_eq!(path.strip_prefix_absolute(invalid_prefix), None);
333    }
334
335    #[test]
336    fn test_strip_suffix() {
337        let path = Path::from_str("/home/user/file.txt");
338        let suffix = Path::from_str("user/file.txt");
339        assert_eq!(path.strip_suffix(suffix).unwrap().as_str(), "/home");
340
341        let invalid_suffix = Path::from_str("user/invalid.txt");
342        assert_eq!(path.strip_suffix(invalid_suffix), None);
343    }
344
345    #[test]
346    fn test_go_parent() {
347        let path = Path::from_str("/home/user/file.txt");
348        assert_eq!(&path.go_parent().unwrap().0, "/home/user");
349        assert_eq!(&path.go_parent().unwrap().go_parent().unwrap().0, "/home");
350        assert_eq!(
351            &path
352                .go_parent()
353                .unwrap()
354                .go_parent()
355                .unwrap()
356                .go_parent()
357                .unwrap()
358                .0,
359            "/"
360        );
361        assert_eq!(
362            path.go_parent()
363                .unwrap()
364                .go_parent()
365                .unwrap()
366                .go_parent()
367                .unwrap()
368                .go_parent(),
369            None
370        );
371
372        let path = Path::from_str("home/user/file.txt");
373        assert_eq!(&path.go_parent().unwrap().0, "home/user");
374        assert_eq!(&path.go_parent().unwrap().go_parent().unwrap().0, "home");
375        assert_eq!(
376            &path
377                .go_parent()
378                .unwrap()
379                .go_parent()
380                .unwrap()
381                .go_parent()
382                .unwrap()
383                .0,
384            ""
385        );
386    }
387
388    #[test]
389    fn test_path_file() {
390        // Regular case
391        let path = Path::from_str("/Directory/File.txt");
392        assert_eq!(path.get_extension(), Some("txt"));
393        assert_eq!(path.get_file_prefix(), Some("File"));
394        assert_eq!(path.get_file_name(), Some("File.txt"));
395
396        // No extension
397        let path = Path::from_str("/Directory/File");
398        assert_eq!(path.get_extension(), None);
399        assert_eq!(path.get_file_prefix(), Some("File"));
400        assert_eq!(path.get_file_name(), Some("File"));
401
402        // No file prefix
403        let path = Path::from_str("File.txt");
404        assert_eq!(path.get_extension(), Some("txt"));
405        assert_eq!(path.get_file_prefix(), Some("File"));
406        assert_eq!(path.get_file_name(), Some("File.txt"));
407
408        // No file prefix or extension
409        let path = Path::from_str("/");
410        assert_eq!(path.get_extension(), None);
411        assert_eq!(path.get_file_prefix(), None);
412        assert_eq!(path.get_file_name(), None);
413
414        // No file prefix or extension
415        let path = Path::from_str("File");
416        assert_eq!(path.get_extension(), None);
417        assert_eq!(path.get_file_prefix(), Some("File"));
418        assert_eq!(path.get_file_name(), Some("File"));
419    }
420}