Skip to main content

qubit_fs/path/
relative_path.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Safe normalized relative logical paths.
10
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fmt::Result as FmtResult;
14
15use crate::error::FsError;
16use crate::error::FsOperation;
17use crate::error::FsResult;
18
19/// A non-empty normalized relative path that cannot escape its base.
20///
21/// # Examples
22///
23/// ```rust
24/// use qubit_fs::path::RelativePath;
25///
26/// let relative = RelativePath::parse("reports/2026")?;
27/// assert_eq!("reports/2026", relative.as_str());
28/// # Ok::<(), qubit_fs::FsError>(())
29/// ```
30#[derive(Clone, Debug, Eq, Hash, PartialEq)]
31pub struct RelativePath(
32    /// Normalized descendant path text.
33    String,
34);
35
36impl RelativePath {
37    /// Parses a normalized relative path.
38    ///
39    /// Returns an invalid-path error for empty or absolute input, NUL, or a
40    /// traversal sequence that escapes above the relative root.
41    ///
42    /// # Parameters
43    /// - `text`: Relative path text to normalize and validate.
44    ///
45    /// # Returns
46    /// Returns the normalized descendant path with redundant separators and
47    /// current-directory components removed.
48    ///
49    /// # Errors
50    /// Returns an invalid-path error when `text` is empty, absolute, contains
51    /// NUL, or escapes above the relative root.
52    pub fn parse(text: &str) -> FsResult<Self> {
53        if text.is_empty() || text.starts_with('/') || text.contains('\0') {
54            return Err(invalid_relative());
55        }
56        let mut components = Vec::new();
57        for component in text.split('/') {
58            match component {
59                "" | "." => {}
60                ".." => {
61                    if components.pop().is_none() {
62                        return Err(invalid_relative());
63                    }
64                }
65                value => components.push(value),
66            }
67        }
68        if components.is_empty() {
69            return Err(invalid_relative());
70        }
71        Ok(Self(components.join("/")))
72    }
73
74    /// Returns the normalized logical path text.
75    #[inline]
76    #[must_use]
77    pub fn as_str(&self) -> &str {
78        &self.0
79    }
80}
81
82impl Display for RelativePath {
83    /// Formats the normalized relative path.
84    ///
85    /// # Parameters
86    /// - `formatter`: Destination for the normalized relative spelling.
87    #[inline]
88    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
89        formatter.write_str(self.as_str())
90    }
91}
92
93/// Builds the shared relative-path validation failure.
94fn invalid_relative() -> FsError {
95    FsError::invalid_path(
96        FsOperation::ParsePath,
97        "relative path must identify a descendant without escaping its base",
98    )
99}