Skip to main content

raf_source/
path.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! The validated root-relative path every [`Tree`](crate::Tree) call takes.
5
6use std::error::Error;
7use std::fmt;
8use std::fmt::Write as _;
9use std::sync::Arc;
10
11use purrdf_lex::allocation::{Admission, Memory, StorageError};
12
13/// A source authority within one load; this handle is not durable source proof.
14///
15/// The first-party tree is authority zero. A catalog assigns other authorities
16/// and records their exact source identities separately.
17#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct SourceAuthorityId(pub(crate) usize);
19
20impl SourceAuthorityId {
21    /// The ordinary first-party tree used by [`RelPath::new`].
22    pub const FIRST_PARTY: Self = Self(0);
23
24    /// The load-local authority number.
25    #[must_use]
26    pub const fn index(self) -> usize {
27        self.0
28    }
29}
30
31/// A path below a tree root: `/`-separated, UTF-8, never absolute and never
32/// leaving the root.
33///
34/// The authority is part of identity, equality and ordering. Its relative text
35/// stays unchanged: [`RelPath::as_str`] alone does not identify a source.
36/// Ordinary constructors select the first-party source; [`RelPath::in_source`]
37/// explicitly selects another independently rooted authority.
38///
39/// The empty path is the root itself. Empty segments and `.` segments are
40/// dropped. A `..` segment is kept, because on a disk it means the parent of
41/// the directory the earlier segments really reach, which differs from the
42/// lexical parent when one of them is a symlink; it is refused only when the
43/// segments before it do not leave a level to climb out of.
44///
45/// The text is shared, so a clone does not copy it.
46#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
47pub struct RelPath {
48    text: Arc<str>,
49    /// The independently rooted source that interprets this relative path.
50    authority: SourceAuthorityId,
51}
52
53/// Why an input is not a [`RelPath`].
54#[derive(Debug, Clone, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum PathError {
57    /// The input starts with `/`.
58    Absolute {
59        /// The refused input.
60        input: String,
61    },
62    /// A `..` segment climbs above the root.
63    AboveRoot {
64        /// The refused input.
65        input: String,
66    },
67    /// The input holds a backslash, which separates segments on some platforms.
68    Backslash {
69        /// The refused input.
70        input: String,
71    },
72    /// The input holds a NUL character.
73    Nul {
74        /// The refused input.
75        input: String,
76    },
77    /// A segment starts with a drive letter and a colon.
78    DriveLetter {
79        /// The refused input.
80        input: String,
81    },
82}
83
84impl PathError {
85    /// The input that was refused.
86    #[must_use]
87    pub fn input(&self) -> &str {
88        match self {
89            Self::Absolute { input }
90            | Self::AboveRoot { input }
91            | Self::Backslash { input }
92            | Self::Nul { input }
93            | Self::DriveLetter { input } => input,
94        }
95    }
96}
97
98impl fmt::Display for PathError {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        let input = crate::error::Esc(self.input());
101        match self {
102            Self::Absolute { .. } => write!(
103                f,
104                "`{input}` is absolute; a path must be relative to the root"
105            ),
106            Self::AboveRoot { .. } => write!(f, "`{input}` climbs above the root with `..`"),
107            Self::Backslash { .. } => write!(
108                f,
109                "`{input}` holds a backslash; segments are separated by `/`"
110            ),
111            Self::Nul { .. } => write!(f, "`{input}` holds a NUL character"),
112            Self::DriveLetter { .. } => write!(
113                f,
114                "`{input}` holds a segment that starts with a drive letter"
115            ),
116        }
117    }
118}
119
120impl Error for PathError {}
121
122fn starts_with_drive_letter(segment: &str) -> bool {
123    let mut chars = segment.chars();
124    chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.next() == Some(':')
125}
126
127/// A borrowed refusal needs no diagnostic allocation during speculation.
128enum JoinRefusal {
129    Absolute,
130    AboveRoot,
131    Backslash,
132    Nul,
133    DriveLetter,
134}
135
136impl JoinRefusal {
137    fn owned(self, input: &str) -> PathError {
138        let input = input.to_owned();
139        match self {
140            Self::Absolute => PathError::Absolute { input },
141            Self::AboveRoot => PathError::AboveRoot { input },
142            Self::Backslash => PathError::Backslash { input },
143            Self::Nul => PathError::Nul { input },
144            Self::DriveLetter => PathError::DriveLetter { input },
145        }
146    }
147}
148
149/// One allocation-free rendering of the validated join's unchanged segments.
150struct JoinedText<'a> {
151    base: &'a RelPath,
152    input: &'a str,
153}
154
155impl fmt::Display for JoinedText<'_> {
156    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
157        for (index, segment) in self.base.joined_segments(self.input).enumerate() {
158            if index != 0 {
159                out.write_str("/")?;
160            }
161            out.write_str(segment)?;
162        }
163        Ok(())
164    }
165}
166
167impl RelPath {
168    /// The root itself.
169    #[must_use]
170    pub fn root() -> Self {
171        Self {
172            text: Arc::from(""),
173            authority: SourceAuthorityId::FIRST_PARTY,
174        }
175    }
176
177    /// Parse `input` as a path below the root.
178    ///
179    /// # Errors
180    ///
181    /// Returns a [`PathError`] when the input is absolute, climbs above the
182    /// root, or holds a backslash, a NUL or a drive-letter segment.
183    pub fn new(input: &str) -> Result<Self, PathError> {
184        Self::root().join(input)
185    }
186
187    /// Whether `input` is already a valid, normalized relative spelling.
188    ///
189    /// Uses the same path checks as [`Self::new`] without allocating text,
190    /// component storage or diagnostics. The empty spelling is the root;
191    /// otherwise empty and `.` components are noncanonical. A `..` component
192    /// remains literal and may only spend depth supplied by preceding components.
193    /// This query does not inspect the filesystem or select a source authority.
194    #[must_use]
195    pub fn is_canonical(input: &str) -> bool {
196        input.is_empty()
197            || (Self::validate_from_depth(input, 0).is_ok()
198                && input.split('/').all(|segment| !matches!(segment, "" | ".")))
199    }
200
201    /// Append `input`, which is read as a relative path.
202    ///
203    /// `.` and empty segments are dropped; `..` segments are kept so that the
204    /// disk, not the text, decides where they lead.
205    ///
206    /// # Errors
207    ///
208    /// Returns a [`PathError`] when the input is absolute, climbs above this
209    /// path's root, or holds a backslash, a NUL or a drive-letter segment.
210    pub fn join(&self, input: &str) -> Result<Self, PathError> {
211        self.validate_join(input)
212            .map_err(|refusal| refusal.owned(input))?;
213        Ok(Self {
214            text: Arc::from(format!("{}", JoinedText { base: self, input })),
215            authority: self.authority,
216        })
217    }
218
219    /// Materialize a candidate under its original admission account.
220    /// Invalid spelling remains the canonical caller's diagnostic responsibility.
221    pub(crate) fn join_admitted<S: Admission + ?Sized>(
222        &self,
223        input: &str,
224        memory: &mut Memory<'_, S>,
225    ) -> Result<Option<Self>, StorageError> {
226        if self.validate_join(input).is_err() {
227            return Ok(None);
228        }
229        let bytes = self.joined_segments(input).enumerate().try_fold(
230            0_usize,
231            |bytes, (index, segment)| {
232                bytes
233                    .checked_add(usize::from(index != 0))
234                    .and_then(|bytes| bytes.checked_add(segment.len()))
235                    .ok_or(StorageError::SizeOverflow)
236            },
237        )?;
238        let shared = Self::shared_layout(bytes)?;
239        memory.scope(|memory| {
240            // Both original UTF-8 scratch and its shared destination coexist.
241            // Reserve the destination before any materialization can start.
242            memory.add_bytes(shared)?;
243            let mut text = String::new();
244            memory.reserve_string(&mut text, bytes)?;
245            write!(&mut text, "{}", JoinedText { base: self, input })
246                .expect("writing validated borrowed segments to String cannot fail");
247            let path = Self {
248                text: Arc::from(text.as_str()),
249                authority: self.authority,
250            };
251            memory.release_string(text)?;
252            Ok(Some(path))
253        })
254    }
255
256    pub(crate) fn owned_layout(&self) -> Result<usize, StorageError> {
257        Self::shared_layout(self.as_str().len())
258    }
259
260    fn shared_layout(bytes: usize) -> Result<usize, StorageError> {
261        bytes
262            .checked_add(2 * size_of::<usize>())
263            .and_then(|bytes| bytes.checked_next_multiple_of(align_of::<usize>()))
264            .ok_or(StorageError::SizeOverflow)
265    }
266
267    fn joined_segments<'a>(&'a self, input: &'a str) -> impl Iterator<Item = &'a str> {
268        self.segments().chain(
269            input
270                .split('/')
271                .filter(|segment| !matches!(*segment, "" | ".")),
272        )
273    }
274
275    fn validate_join(&self, input: &str) -> Result<(), JoinRefusal> {
276        let mut depth = 0_usize;
277        for segment in self.segments() {
278            // Every prefix of this already validated path stays inside its root.
279            if segment == ".." {
280                depth -= 1;
281            } else {
282                depth += 1;
283            }
284        }
285        Self::validate_from_depth(input, depth)
286    }
287
288    fn validate_from_depth(input: &str, mut depth: usize) -> Result<(), JoinRefusal> {
289        if input.starts_with('/') {
290            return Err(JoinRefusal::Absolute);
291        }
292        if input.contains('\\') {
293            return Err(JoinRefusal::Backslash);
294        }
295        if input.contains('\0') {
296            return Err(JoinRefusal::Nul);
297        }
298        for segment in input.split('/') {
299            match segment {
300                "" | "." => {}
301                ".." => {
302                    depth = depth.checked_sub(1).ok_or(JoinRefusal::AboveRoot)?;
303                }
304                _ => {
305                    if starts_with_drive_letter(segment) {
306                        return Err(JoinRefusal::DriveLetter);
307                    }
308                    depth += 1;
309                }
310            }
311        }
312        Ok(())
313    }
314
315    /// The independently rooted source of this path.
316    #[must_use]
317    pub const fn authority(&self) -> SourceAuthorityId {
318        self.authority
319    }
320
321    /// Explicitly select an authority for this same relative spelling.
322    ///
323    /// A load-local handle selects a source; it does not authenticate its bytes.
324    /// Module traversal never changes authority this way.
325    #[must_use]
326    pub fn in_source(&self, authority: SourceAuthorityId) -> Self {
327        Self {
328            text: self.text.clone(),
329            authority,
330        }
331    }
332
333    /// The root of this path's own source authority.
334    #[must_use]
335    pub fn source_root(&self) -> Self {
336        Self::root().in_source(self.authority)
337    }
338
339    /// True for the root itself.
340    #[must_use]
341    pub fn is_root(&self) -> bool {
342        self.text.is_empty()
343    }
344
345    /// The path as `/`-separated text; the root is the empty string.
346    #[must_use]
347    pub fn as_str(&self) -> &str {
348        &self.text
349    }
350
351    /// The segments in order, `..` included.
352    pub fn segments(&self) -> impl Iterator<Item = &str> {
353        self.text.split('/').filter(|segment| !segment.is_empty())
354    }
355
356    /// The last segment, or `None` for the root.
357    #[must_use]
358    pub fn file_name(&self) -> Option<&str> {
359        self.segments().last()
360    }
361
362    /// This path without its last segment, or `None` for the root.
363    ///
364    /// The result is lexical: when the last segment is `..` it is not the
365    /// directory the path leads out of.
366    #[must_use]
367    pub fn parent(&self) -> Option<Self> {
368        if self.is_root() {
369            return None;
370        }
371        let text = self.text.rfind('/').map_or("", |index| &self.text[..index]);
372        Some(Self {
373            text: Arc::from(text),
374            authority: self.authority,
375        })
376    }
377}
378
379impl fmt::Display for RelPath {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        if self.is_root() {
382            f.write_str(".")
383        } else {
384            f.write_str(&self.text)
385        }
386    }
387}
388
389#[cfg(test)]
390mod display_tests {
391    use super::RelPath;
392
393    #[test]
394    fn control_characters_in_a_refused_path_are_escaped() {
395        let refused = RelPath::new("/a\u{1b}[31m\u{202e}b").expect_err("absolute");
396        let text = refused.to_string();
397        assert!(!text.contains('\u{1b}'), "{text}");
398        assert!(!text.contains('\u{202e}'), "{text}");
399        assert!(text.contains("\\u{1b}"), "{text}");
400    }
401}