Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_file/src/relpath.rs

4.4 KiB, 1 run

created by r1870400018:74069, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! One spelling for a path relative to a root, refused rather than repaired.
2//!
3//! A path that arrives from outside -- a model's tool call, a stored reference, a user's mark --
4//! was checked in several places, and each place tidied it differently: one trimmed whitespace,
5//! one resolved `..`, one collapsed `a//b`. A guard that tidied one way and an act that tidied
6//! another then disagreed about which file was meant, and a mark on the folder `" sp"` went into
7//! force as `sp` (Daimond HIST-SAFE U2 QA F1, 12 Oct 2026). [`RelPath`] has no tidying at all: a
8//! string either already is its one canonical form, or it is refused with the reason, so a guard
9//! and the act it guards can only ever see the same string.
10//!
11//! [Written with AI](https://need2know.ai/with-ai/code)\
12//! Anthropic Claude
13
14use oxedyne_fe2o3_core::prelude::*;
15
16use std::fmt;
17
18
19/// Why a string is not a [`RelPath`].
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Fault {
22 Empty, // "", which names no place
23 Absolute, // a leading "/"
24 Backslash, // "\", a separator on one platform and a name character on another
25 Control, // NUL, a tab or any other control character
26 EmptySegment, // "a//b", or a trailing "/"
27 Dot, // a "." segment, including "." alone
28 DotDot, // a ".." segment, which climbs
29 EdgeSpace, // a segment that begins or ends with whitespace
30}
31
32impl fmt::Display for Fault {
33 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 f.write_str(match self {
35 Self::Empty => "it is empty",
36 Self::Absolute => "it begins with '/', so it is absolute",
37 Self::Backslash => "it holds a backslash; the separator is '/'",
38 Self::Control => "it holds a control character",
39 Self::EmptySegment => "it has an empty segment ('//' or a trailing '/')",
40 Self::Dot => "it has a '.' segment",
41 Self::DotDot => "it has a '..' segment",
42 Self::EdgeSpace => "a segment begins or ends with whitespace",
43 })
44 }
45}
46
47/// A non-empty path relative to a root, in its one canonical form: segments joined by `/`, none
48/// empty, none `.` or `..`, none with whitespace at either edge, and no backslash or control
49/// character anywhere. Made only by [`RelPath::parse`], so holding one is the proof.
50#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
51pub struct RelPath(String);
52
53impl RelPath {
54
55 /// Why `s` is not canonical, or `None` where it is. The one rule; [`RelPath::parse`] is this
56 /// with an error that names the value.
57 pub fn fault(s: &str) -> Option<Fault> {
58 if s.is_empty() {
59 return Some(Fault::Empty);
60 }
61 if s.starts_with('/') {
62 return Some(Fault::Absolute);
63 }
64 if s.contains('\\') {
65 return Some(Fault::Backslash);
66 }
67 if s.chars().any(char::is_control) {
68 return Some(Fault::Control);
69 }
70 for seg in s.split('/') {
71 match seg {
72 "" => return Some(Fault::EmptySegment),
73 "." => return Some(Fault::Dot),
74 ".." => return Some(Fault::DotDot),
75 _ => (),
76 }
77 let edge = |c: Option<char>| c.is_some_and(char::is_whitespace);
78 if edge(seg.chars().next()) || edge(seg.chars().next_back()) {
79 return Some(Fault::EdgeSpace);
80 }
81 }
82 None
83 }
84
85 /// Is `s` already a canonical relative path?
86 pub fn is_canonical(s: &str) -> bool {
87 Self::fault(s).is_none()
88 }
89
90 pub fn parse(s: &str) -> Outcome<Self> {
91 match Self::fault(s) {
92 None => Ok(Self(s.to_string())),
93 Some(why) => Err(err!(
94 "The relative path {:?} is refused: {}.", s, why;
95 Invalid, Input)),
96 }
97 }
98
99 pub fn as_str(&self) -> &str { &self.0 }
100
101 pub fn into_string(self) -> String { self.0 }
102
103 pub fn segments(&self) -> std::str::Split<'_, char> { self.0.split('/') }
104
105 /// The last segment.
106 pub fn name(&self) -> &str {
107 match self.0.rfind('/') {
108 Some(i) => &self.0[i + 1..],
109 None => &self.0,
110 }
111 }
112
113 /// The path less its last segment, `None` for a single segment.
114 pub fn parent(&self) -> Option<Self> {
115 self.0.rfind('/').map(|i| Self(self.0[..i].to_string()))
116 }
117
118 /// `self` then `rest`, which is canonical because both are.
119 pub fn join(&self, rest: &Self) -> Self {
120 Self(fmt!("{}/{}", self.0, rest.0))
121 }
122
123 /// Is `self` `base` or beneath it, by whole segments, so `ab` is not within `a`?
124 pub fn is_within(&self, base: &Self) -> bool {
125 self.0 == base.0
126 || (self.0.len() > base.0.len()
127 && self.0.starts_with(&base.0)
128 && self.0.as_bytes()[base.0.len()] == b'/')
129 }
130}
131
132impl fmt::Display for RelPath {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 f.write_str(&self.0)
135 }
136}
137
138impl AsRef<str> for RelPath {
139 fn as_ref(&self) -> &str { &self.0 }
140}