qubit_fs/path/path_component.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//! One validated logical path component.
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 logical component that cannot express hierarchy or traversal.
20///
21/// # Examples
22///
23/// ```rust
24/// use qubit_fs::path::PathComponent;
25///
26/// let component = PathComponent::parse("reports")?;
27/// assert_eq!("reports", component.as_str());
28/// # Ok::<(), qubit_fs::FsError>(())
29/// ```
30#[derive(Clone, Debug, Eq, Hash, PartialEq)]
31pub struct PathComponent(
32 /// Validated component text containing no hierarchy or traversal marker.
33 String,
34);
35
36impl PathComponent {
37 /// Parses one logical component.
38 ///
39 /// Returns an invalid-path error for empty input, separators, traversal
40 /// markers, or NUL. This method performs no native-path conversion.
41 ///
42 /// # Parameters
43 /// - `text`: Component text to validate.
44 ///
45 /// # Returns
46 /// Returns the validated component.
47 ///
48 /// # Errors
49 /// Returns an invalid-path error when `text` is empty, contains a
50 /// separator, is a traversal marker, or contains NUL.
51 pub fn parse(text: &str) -> FsResult<Self> {
52 if text.is_empty() || matches!(text, "." | "..") || text.contains('/') || text.contains('\0') {
53 return Err(FsError::invalid_path(
54 FsOperation::ParsePath,
55 "path component must be a non-empty non-traversal component",
56 ));
57 }
58 Ok(Self(text.to_owned()))
59 }
60
61 /// Returns the validated logical component text.
62 #[inline]
63 #[must_use]
64 pub fn as_str(&self) -> &str {
65 &self.0
66 }
67}
68
69impl Display for PathComponent {
70 /// Formats the validated component without changing its lexical spelling.
71 ///
72 /// # Parameters
73 /// - `formatter`: Destination for the component text.
74 #[inline]
75 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
76 formatter.write_str(self.as_str())
77 }
78}