1use 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#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct SourceAuthorityId(pub(crate) usize);
19
20impl SourceAuthorityId {
21 pub const FIRST_PARTY: Self = Self(0);
23
24 #[must_use]
26 pub const fn index(self) -> usize {
27 self.0
28 }
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
47pub struct RelPath {
48 text: Arc<str>,
49 authority: SourceAuthorityId,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum PathError {
57 Absolute {
59 input: String,
61 },
62 AboveRoot {
64 input: String,
66 },
67 Backslash {
69 input: String,
71 },
72 Nul {
74 input: String,
76 },
77 DriveLetter {
79 input: String,
81 },
82}
83
84impl PathError {
85 #[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
127enum 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
149struct 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 #[must_use]
170 pub fn root() -> Self {
171 Self {
172 text: Arc::from(""),
173 authority: SourceAuthorityId::FIRST_PARTY,
174 }
175 }
176
177 pub fn new(input: &str) -> Result<Self, PathError> {
184 Self::root().join(input)
185 }
186
187 #[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 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 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 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 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 #[must_use]
317 pub const fn authority(&self) -> SourceAuthorityId {
318 self.authority
319 }
320
321 #[must_use]
326 pub fn in_source(&self, authority: SourceAuthorityId) -> Self {
327 Self {
328 text: self.text.clone(),
329 authority,
330 }
331 }
332
333 #[must_use]
335 pub fn source_root(&self) -> Self {
336 Self::root().in_source(self.authority)
337 }
338
339 #[must_use]
341 pub fn is_root(&self) -> bool {
342 self.text.is_empty()
343 }
344
345 #[must_use]
347 pub fn as_str(&self) -> &str {
348 &self.text
349 }
350
351 pub fn segments(&self) -> impl Iterator<Item = &str> {
353 self.text.split('/').filter(|segment| !segment.is_empty())
354 }
355
356 #[must_use]
358 pub fn file_name(&self) -> Option<&str> {
359 self.segments().last()
360 }
361
362 #[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}