Skip to main content

sark_http/uri/target/relative/
mod.rs

1use std::iter;
2
3pub(super) mod raw;
4
5use crate::uri::target::{self, Error, Origin, Slash, Target};
6
7/// An admitted relative or origin-form path and optional query.
8#[derive(Clone, Copy)]
9pub struct Relative<'a> {
10    pub(super) value: &'a str,
11    pub(super) path_end: u32,
12}
13
14impl<'a> Relative<'a> {
15    pub(super) fn from_target(target: &'a Target) -> Self {
16        Self {
17            value: target.path_query(),
18            path_end: target.path_end - target.head.end,
19        }
20    }
21
22    pub fn parse(value: &'a str) -> Result<Self, Error> {
23        Ok(Self {
24            value,
25            path_end: target::path_end(value)?,
26        })
27    }
28
29    /// Resolves only admitted components; normalization cannot introduce new bytes
30    /// other than path separators, so the original grammar proof remains valid.
31    /// Materialization precedes offset narrowing.
32    pub fn resolve(self, base: &Target) -> Result<Target, Error> {
33        if self.value.is_empty() {
34            return base.try_clone().map_err(Error::Allocation);
35        }
36        if self.value.starts_with('/') && !self.has_dots() {
37            return base.with_origin(Origin {
38                value: self.value,
39                path_end: self.path_end,
40                slash: Slash::Present,
41            });
42        }
43        target::raw::resolve(self, base)
44    }
45
46    pub(super) fn has_dots(self) -> bool {
47        target::raw::split(self)
48            .0
49            .split('/')
50            .any(|part| matches!(part, "." | ".."))
51    }
52}
53
54/// Yields normalized segments from the end without storing or joining them.
55/// `prefix` excludes the root slash and ends at a directory separator.
56pub(super) fn segments<'a>(
57    prefix: &'a str,
58    path: &'a str,
59) -> impl Iterator<Item = &'a str> + Clone {
60    let trailing = matches!(path.rsplit('/').next(), Some("." | ".."));
61    let mut parents = 0usize;
62    iter::once("").take(usize::from(trailing)).chain(
63        path.rsplit('/')
64            .chain(prefix.rsplit_terminator('/'))
65            .filter(move |part| match *part {
66                "." => false,
67                ".." => {
68                    parents += 1;
69                    false
70                }
71                _ if parents != 0 => {
72                    parents -= 1;
73                    false
74                }
75                _ => true,
76            }),
77    )
78}