qubit_fs/path/path_components.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//! Iteration over lexical logical path components.
10
11/// Iterator over the path's lexical component boundaries.
12///
13/// # Examples
14///
15/// ```rust
16/// use qubit_fs::path::{Path, PathComponents};
17///
18/// let path = Path::parse("/a/b")?;
19/// let components: PathComponents<'_> = path.components();
20/// assert_eq!(2, components.count());
21/// # Ok::<(), qubit_fs::FsError>(())
22/// ```
23#[derive(Clone, Debug)]
24pub struct PathComponents<'a> {
25 /// Remaining lexical text with an absolute leading separator removed.
26 remaining: Option<&'a str>,
27}
28
29impl<'a> PathComponents<'a> {
30 /// Creates an iterator for `text`, removing only the absolute root marker.
31 ///
32 /// # Parameters
33 /// - `text`: Lexical path text to iterate over.
34 /// - `absolute`: Whether `text` starts at a logical root.
35 /// - `literal`: Whether separators in `text` must remain literal.
36 ///
37 /// # Returns
38 /// An iterator over the remaining lexical components.
39 pub(crate) fn new(text: &'a str, absolute: bool, literal: bool) -> Self {
40 let text = if absolute && !literal {
41 text.strip_prefix('/').unwrap_or(text)
42 } else {
43 text
44 };
45 Self {
46 remaining: (!text.is_empty()).then_some(text),
47 }
48 }
49}
50
51impl<'a> Iterator for PathComponents<'a> {
52 /// Borrowed text for one lexical path component.
53 type Item = &'a str;
54
55 /// Returns the next lexical component, including empty literal components.
56 ///
57 /// # Returns
58 /// `Some` with the next component, or `None` when no component remains.
59 fn next(&mut self) -> Option<Self::Item> {
60 let remaining = self.remaining?;
61 match remaining.split_once('/') {
62 Some((component, rest)) => {
63 self.remaining = Some(rest);
64 Some(component)
65 }
66 None => {
67 self.remaining = None;
68 Some(remaining)
69 }
70 }
71 }
72}