Skip to main content

storage_kit/ns/
path.rs

1//! [`NsPath`]: a validated namespace path, and the portable name grammar every backend enforces through it.
2//!
3//! The grammar is one deliberately strict subset of what Linux, macOS and Windows each allow. The point is that a name
4//! accepted here is legal, unambiguous and round-trippable on every platform, so "it worked on my Linux box and then
5//! collided on the Mac" is refused at the namespace, not discovered at a backend. It is intentionally stricter than any
6//! single OS: the rules below are not "what the host would accept".
7//!
8//! A path is absolute (`/a/b`), `/`-separated, and the root is `/`. There is no relative form, no `.`/`..`, no `//`, no
9//! trailing `/`. A name is refused (never silently repaired) when it:
10//!
11//! - is empty, `.` or `..`;
12//! - is not already in Unicode **NFC** (the namespace never normalises, because normalising silently changes which
13//!   entry a caller addressed);
14//! - contains a control character (`char::is_control`, so C0, DEL and C1), a **format character** from the fixed list
15//!   in [`is_format_character`] (bidirectional controls, zero-width spaces, the soft hyphen, the byte-order mark: all
16//!   invisible or reordering characters), `\`, `:` or any of `<>"|?*`;
17//! - ends in a dot or a space (Windows strips them, so the name would not round-trip);
18//! - is a Windows reserved device name (`CON PRN AUX NUL COM1-9 LPT1-9`, plus `CONIN$`, `CONOUT$` and the superscript
19//!   digit forms), case-insensitively, with or without an extension (`con.txt` is as reserved as `CON`);
20//! - is longer than [`MAX_NAME_BYTES`] (255) UTF-8 bytes, or the whole path is longer than [`MAX_PATH_BYTES`] (4096);
21//! - begins with [`TEMP_PREFIX`] (compared case-folded, so `.SKNS-TMP-` on a case-insensitive volume is refused too),
22//!   which `HostDir` reserves for its atomic-replace temporary files.
23//!
24//! Why the format characters: a name is something a person reads (a confirmation diff of a launcher entry, a file
25//! manager, a log line). A name that can *display* as something other than what it *is* (a right-to-left override that
26//! reverses `txt.exe` into `exe.txt`, a zero-width space that makes two different names look identical) lets one entry
27//! impersonate another in front of the person deciding. The list is fixed, not a Unicode category lookup, so a Unicode
28//! update cannot silently change which names are legal. Zero-width joiner (U+200D) and non-joiner (U+200C) stay legal:
29//! scripts such as Persian, Devanagari and emoji sequences need them.
30//!
31//! Two names that differ only by case (or only by Unicode normalisation form) are **distinct paths** but cannot
32//! *coexist* in one directory: creating the second is refused with `CaseCollision` (see [`case_fold_key`]), on every
33//! backend, even a case-sensitive one.
34
35use std::fmt;
36use std::str::FromStr;
37
38use super::error::{NsError, NsErrorKind};
39
40/// Longest single path component, in UTF-8 bytes. Matches the limit of ext4, APFS, NTFS and most others.
41pub const MAX_NAME_BYTES: usize = 255;
42
43/// Longest whole path, in UTF-8 bytes, separators included.
44pub const MAX_PATH_BYTES: usize = 4096;
45
46/// The prefix `HostDir` gives its temporary files while it does an atomic replace.
47///
48/// Reserved so a temp file can never collide with, or be mistaken for, a name a caller created: the grammar refuses it
49/// ([`PathReason::ReservedPrefix`]) and `HostDir`'s listing hides anything that starts with it. A temp file left behind
50/// by a crash is therefore invisible to the namespace; it can be removed from the host directory by hand.
51pub const TEMP_PREFIX: &str = ".skns-tmp-";
52
53/// Why a path or name was refused. Carried by [`NsErrorKind::InvalidPath`].
54///
55/// Deliberately carries no part of the offending input: the input may be hostile or may be a host path, and an error
56/// message is not the place to echo it.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58#[non_exhaustive]
59pub enum PathReason {
60    /// The path does not start with `/`. Namespace paths are always absolute; a host path such as `C:\x` or `a/b` is not
61    /// one.
62    NotAbsolute,
63    /// An empty component: `//`, or a trailing `/`.
64    EmptyComponent,
65    /// A `.` component.
66    DotComponent,
67    /// A `..` component. The namespace has no parent traversal; ask for the parent's path.
68    DotDotComponent,
69    /// A control character (C0, DEL or C1).
70    ControlCharacter,
71    /// An invisible or direction-changing format character (see [`is_format_character`]).
72    FormatCharacter,
73    /// One of `\ : < > " | ? *`.
74    ForbiddenCharacter,
75    /// The name is not in Unicode NFC. Normalise it before asking.
76    NotNfc,
77    /// The name ends in `.` or a space.
78    TrailingDotOrSpace,
79    /// A Windows reserved device name (`CON`, `NUL`, `COM1`, ...), with or without an extension.
80    ReservedName,
81    /// The name starts with [`TEMP_PREFIX`].
82    ReservedPrefix,
83    /// A component longer than [`MAX_NAME_BYTES`].
84    NameTooLong,
85    /// A path longer than [`MAX_PATH_BYTES`].
86    PathTooLong,
87}
88
89impl PathReason {
90    pub(crate) fn describe(self) -> &'static str {
91        match self {
92            PathReason::NotAbsolute => {
93                "a namespace path starts with '/' (a host path or a relative path is not one)"
94            }
95            PathReason::EmptyComponent => "an empty component ('//' or a trailing '/')",
96            PathReason::DotComponent => "a '.' component",
97            PathReason::DotDotComponent => {
98                "a '..' component (there is no parent traversal; give the parent's path)"
99            }
100            PathReason::ControlCharacter => "a control character in a name",
101            PathReason::FormatCharacter => {
102                "an invisible or direction-changing format character in a name (bidi control, zero-width space, soft hyphen, BOM)"
103            }
104            PathReason::ForbiddenCharacter => {
105                "a character that is not portable in a name (one of \\ : < > \" | ? *)"
106            }
107            PathReason::NotNfc => "a name that is not Unicode NFC (normalise it first)",
108            PathReason::TrailingDotOrSpace => "a name ending in '.' or a space",
109            PathReason::ReservedName => "a Windows reserved device name (CON, NUL, COM1, ...)",
110            PathReason::ReservedPrefix => "a name starting with the reserved temporary prefix",
111            PathReason::NameTooLong => "a name longer than 255 bytes",
112            PathReason::PathTooLong => "a path longer than 4096 bytes",
113        }
114    }
115}
116
117/// A validated namespace path: absolute, `/`-separated, every component inside the portable name grammar. See the
118/// [module docs](self) for the grammar.
119///
120/// Holding an `NsPath` is proof the grammar was checked, so a backend does not re-parse strings and cannot be handed a
121/// `..` or a host path by construction.
122#[derive(Clone, PartialEq, Eq, Hash)]
123pub struct NsPath(String);
124
125impl NsPath {
126    /// The root, `/`.
127    pub fn root() -> Self {
128        NsPath("/".to_string())
129    }
130
131    /// Validate and wrap a namespace path.
132    ///
133    /// ```
134    /// # #[cfg(feature = "ns")] {
135    /// use storage_kit::ns::{NsPath, NsErrorKind, PathReason};
136    /// assert!(NsPath::parse("/config/apps.toml").is_ok());
137    /// let err = NsPath::parse("/config/../etc").unwrap_err();
138    /// assert_eq!(err.kind(), NsErrorKind::InvalidPath(PathReason::DotDotComponent));
139    /// # }
140    /// ```
141    pub fn parse(input: &str) -> Result<Self, NsError> {
142        let invalid = |r| NsError::new(NsErrorKind::InvalidPath(r));
143        if input.len() > MAX_PATH_BYTES {
144            return Err(invalid(PathReason::PathTooLong));
145        }
146        let Some(rest) = input.strip_prefix('/') else {
147            return Err(invalid(PathReason::NotAbsolute));
148        };
149        if rest.is_empty() {
150            return Ok(Self::root());
151        }
152        for name in rest.split('/') {
153            validate_name(name).map_err(invalid)?;
154        }
155        Ok(NsPath(input.to_string()))
156    }
157
158    /// The path as a string, e.g. `/a/b`. The root is `/`.
159    pub fn as_str(&self) -> &str {
160        &self.0
161    }
162
163    /// True for `/`.
164    pub fn is_root(&self) -> bool {
165        self.0 == "/"
166    }
167
168    /// Number of components; the root has 0.
169    pub fn depth(&self) -> usize {
170        self.components().count()
171    }
172
173    /// Append a **relative** path (`name` or `a/b`), validating every component.
174    ///
175    /// A leading `/` is refused (it reads as an empty first component): to combine two absolute namespace paths use
176    /// [`NsPath::rebase`].
177    pub fn join(&self, relative: &str) -> Result<NsPath, NsError> {
178        let invalid = |r| NsError::new(NsErrorKind::InvalidPath(r));
179        if relative.is_empty() {
180            return Err(invalid(PathReason::EmptyComponent));
181        }
182        for name in relative.split('/') {
183            validate_name(name).map_err(invalid)?;
184        }
185        let mut s = if self.is_root() {
186            String::new()
187        } else {
188            self.0.clone()
189        };
190        s.push('/');
191        s.push_str(relative);
192        if s.len() > MAX_PATH_BYTES {
193            return Err(invalid(PathReason::PathTooLong));
194        }
195        Ok(NsPath(s))
196    }
197
198    /// Append one component that the caller has already validated (a name read back from a backend that enforces the
199    /// grammar). `None` if the result would exceed [`MAX_PATH_BYTES`].
200    pub(crate) fn child(&self, name: &str) -> Option<NsPath> {
201        debug_assert!(validate_name(name).is_ok());
202        let mut s = if self.is_root() {
203            String::new()
204        } else {
205            self.0.clone()
206        };
207        s.push('/');
208        s.push_str(name);
209        (s.len() <= MAX_PATH_BYTES).then_some(NsPath(s))
210    }
211
212    /// The parent directory, or `None` for the root.
213    pub fn parent(&self) -> Option<NsPath> {
214        if self.is_root() {
215            return None;
216        }
217        let idx = self.0.rfind('/')?;
218        Some(if idx == 0 {
219            Self::root()
220        } else {
221            NsPath(self.0[..idx].to_string())
222        })
223    }
224
225    /// The last component, or `None` for the root.
226    pub fn file_name(&self) -> Option<&str> {
227        if self.is_root() {
228            None
229        } else {
230            self.0.rsplit('/').next()
231        }
232    }
233
234    /// The components, in order. Empty for the root.
235    pub fn components(&self) -> impl DoubleEndedIterator<Item = &str> + Clone {
236        self.0.split('/').filter(|c| !c.is_empty())
237    }
238
239    /// True if `base` is this path or one of its ancestors, compared by whole components (`/ab` does not start with
240    /// `/a`). Every path starts with the root.
241    pub fn starts_with(&self, base: &NsPath) -> bool {
242        if base.is_root() || self == base {
243            return true;
244        }
245        self.0
246            .strip_prefix(base.0.as_str())
247            .is_some_and(|rest| rest.starts_with('/'))
248    }
249
250    /// The path below `base`, re-rooted at `/`: `/a/b/c` stripped of `/a` is `/b/c`; stripped of itself it is `/`.
251    /// `None` if `base` is not a prefix. This is how a mount-relative path is derived.
252    pub fn strip_prefix(&self, base: &NsPath) -> Option<NsPath> {
253        if !self.starts_with(base) {
254            return None;
255        }
256        if base.is_root() {
257            return Some(self.clone());
258        }
259        let rest = &self.0[base.0.len()..];
260        Some(if rest.is_empty() {
261            Self::root()
262        } else {
263            NsPath(rest.to_string())
264        })
265    }
266
267    /// The components as case-fold keys: how mounts are matched (a mount at `/Config` also answers to `/config`).
268    pub(crate) fn fold_components(&self) -> Vec<String> {
269        self.components().map(case_fold_key).collect()
270    }
271
272    /// The path made of this path's components after the first `skip`, re-rooted at `/`.
273    pub(crate) fn tail_after(&self, skip: usize) -> NsPath {
274        let mut out = String::new();
275        for c in self.components().skip(skip) {
276            out.push('/');
277            out.push_str(c);
278        }
279        if out.is_empty() {
280            NsPath::root()
281        } else {
282            NsPath(out)
283        }
284    }
285
286    /// The inverse of [`NsPath::strip_prefix`]: place this (mount-relative, `/`-rooted) path under `base`.
287    pub fn rebase(&self, base: &NsPath) -> Result<NsPath, NsError> {
288        if base.is_root() {
289            return Ok(self.clone());
290        }
291        if self.is_root() {
292            return Ok(base.clone());
293        }
294        let s = format!("{}{}", base.0, self.0);
295        if s.len() > MAX_PATH_BYTES {
296            return Err(NsError::new(NsErrorKind::InvalidPath(
297                PathReason::PathTooLong,
298            )));
299        }
300        Ok(NsPath(s))
301    }
302}
303
304impl PartialOrd for NsPath {
305    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
306        Some(self.cmp(other))
307    }
308}
309
310/// Component-wise order, so a directory sorts before its contents and `/a/b` sorts before `/a-b` (a plain string
311/// comparison would put `/a-b` first because `-` sorts before `/`).
312impl Ord for NsPath {
313    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
314        self.components().cmp(other.components())
315    }
316}
317
318impl fmt::Display for NsPath {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        f.write_str(&self.0)
321    }
322}
323
324impl fmt::Debug for NsPath {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        write!(f, "NsPath({:?})", self.0)
327    }
328}
329
330impl FromStr for NsPath {
331    type Err = NsError;
332    fn from_str(s: &str) -> Result<Self, Self::Err> {
333        NsPath::parse(s)
334    }
335}
336
337const FORBIDDEN: &[char] = &['\\', ':', '<', '>', '"', '|', '?', '*'];
338
339/// Check one component against the portable grammar. This is the single validator: `NsPath` uses it, and a backend that
340/// reads names back from a host directory uses it to decide which entries are addressable at all.
341pub fn validate_name(name: &str) -> Result<(), PathReason> {
342    if name.is_empty() {
343        return Err(PathReason::EmptyComponent);
344    }
345    if name == "." {
346        return Err(PathReason::DotComponent);
347    }
348    if name == ".." {
349        return Err(PathReason::DotDotComponent);
350    }
351    if name.len() > MAX_NAME_BYTES {
352        return Err(PathReason::NameTooLong);
353    }
354    for c in name.chars() {
355        if c.is_control() {
356            return Err(PathReason::ControlCharacter);
357        }
358        if is_format_character(c) {
359            return Err(PathReason::FormatCharacter);
360        }
361        if FORBIDDEN.contains(&c) {
362            return Err(PathReason::ForbiddenCharacter);
363        }
364    }
365    if !unicode_normalization::is_nfc(name) {
366        return Err(PathReason::NotNfc);
367    }
368    if name.ends_with('.') || name.ends_with(' ') {
369        return Err(PathReason::TrailingDotOrSpace);
370    }
371    if is_reserved_device_name(name) {
372        return Err(PathReason::ReservedName);
373    }
374    // Folded, so `.SKNS-TMP-1` is refused too: on a case-insensitive volume it IS a temporary file.
375    if case_fold_key(name).starts_with(TEMP_PREFIX) {
376        return Err(PathReason::ReservedPrefix);
377    }
378    Ok(())
379}
380
381/// The characters the grammar refuses as *format characters*: a fixed list, deliberately not a Unicode category.
382///
383/// U+00AD soft hyphen; U+061C Arabic letter mark; U+180E Mongolian vowel separator; U+200B zero-width space;
384/// U+200E and U+200F left-to-right and right-to-left marks; U+202A to U+202E bidirectional embeddings and overrides;
385/// U+2060 to U+2064 word joiner and invisible operators; U+2066 to U+2069 bidirectional isolates; U+FEFF byte-order mark.
386/// U+200C (zero-width non-joiner) and U+200D (zero-width joiner) are **not** on the list.
387pub fn is_format_character(c: char) -> bool {
388    matches!(
389        c,
390        '\u{00AD}'
391            | '\u{061C}'
392            | '\u{180E}'
393            | '\u{200B}'
394            | '\u{200E}'..='\u{200F}'
395            | '\u{202A}'..='\u{202E}'
396            | '\u{2060}'..='\u{2064}'
397            | '\u{2066}'..='\u{2069}'
398            | '\u{FEFF}'
399    )
400}
401
402/// Windows treats the part of a name before its first dot as the device name, ignoring trailing spaces in that part.
403fn is_reserved_device_name(name: &str) -> bool {
404    let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ');
405    let up = stem.to_uppercase();
406    match up.as_str() {
407        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" => true,
408        _ => {
409            let digit = |rest: &str| {
410                matches!(
411                    rest,
412                    "1" | "2"
413                        | "3"
414                        | "4"
415                        | "5"
416                        | "6"
417                        | "7"
418                        | "8"
419                        | "9"
420                        | "\u{b9}"
421                        | "\u{b2}"
422                        | "\u{b3}"
423                )
424            };
425            up.strip_prefix("COM")
426                .or_else(|| up.strip_prefix("LPT"))
427                .is_some_and(digit)
428        }
429    }
430}
431
432/// The key under which two names count as "the same name differing only by case or normalisation form".
433///
434/// `NFC(lowercase(uppercase(NFC(name))))`: an approximation of full Unicode case folding (so `ß` meets `SS`), then
435/// normalised again because case mapping can denormalise. Two consequences matter. It is intentionally a bit
436/// **stricter** than most volumes: a false collision costs a caller a rename, a missed one costs a file silently
437/// overwriting another on macOS or Windows. And an NFD-spelled name that already exists on disk (APFS and HFS+ keep
438/// whatever form they were given, and treat the forms as the same name) has the same key as its NFC twin, so the twin
439/// cannot be created over it. It does not model locale rules (Turkish dotless i).
440pub fn case_fold_key(name: &str) -> String {
441    use unicode_normalization::UnicodeNormalization;
442    let composed: String = name.nfc().collect();
443    composed.to_uppercase().to_lowercase().nfc().collect()
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    #[test]
451    fn root_and_basics() {
452        let r = NsPath::root();
453        assert!(r.is_root());
454        assert_eq!(r.parent(), None);
455        assert_eq!(r.file_name(), None);
456        assert_eq!(r.depth(), 0);
457        let p = NsPath::parse("/a/b/c").unwrap();
458        assert_eq!(p.file_name(), Some("c"));
459        assert_eq!(p.parent().unwrap().as_str(), "/a/b");
460        assert_eq!(NsPath::parse("/a").unwrap().parent().unwrap(), r);
461        assert_eq!(p.components().collect::<Vec<_>>(), ["a", "b", "c"]);
462    }
463
464    #[test]
465    fn prefix_ops_use_whole_components() {
466        let a = NsPath::parse("/a").unwrap();
467        let ab = NsPath::parse("/ab").unwrap();
468        let a_b = NsPath::parse("/a/b").unwrap();
469        assert!(a_b.starts_with(&a));
470        assert!(!ab.starts_with(&a));
471        assert!(a.starts_with(&a));
472        assert!(a.starts_with(&NsPath::root()));
473        assert_eq!(a_b.strip_prefix(&a).unwrap().as_str(), "/b");
474        assert!(a.strip_prefix(&a).unwrap().is_root());
475        assert_eq!(ab.strip_prefix(&a), None);
476        assert_eq!(a_b.strip_prefix(&NsPath::root()).unwrap(), a_b);
477        let b = NsPath::parse("/b").unwrap();
478        assert_eq!(b.rebase(&a).unwrap().as_str(), "/a/b");
479        assert_eq!(NsPath::root().rebase(&a).unwrap(), a);
480    }
481
482    #[test]
483    fn order_is_by_component() {
484        let mut v = [
485            NsPath::parse("/a-b").unwrap(),
486            NsPath::parse("/a/b").unwrap(),
487            NsPath::parse("/a").unwrap(),
488        ];
489        v.sort();
490        let s: Vec<_> = v.iter().map(NsPath::as_str).collect();
491        assert_eq!(s, ["/a", "/a/b", "/a-b"]);
492    }
493
494    #[test]
495    fn join_validates_each_component() {
496        let a = NsPath::parse("/a").unwrap();
497        assert_eq!(a.join("b/c").unwrap().as_str(), "/a/b/c");
498        assert_eq!(NsPath::root().join("x").unwrap().as_str(), "/x");
499        assert!(a.join("/b").is_err());
500        assert!(a.join("b/../c").is_err());
501        assert!(a.join("").is_err());
502    }
503}