sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::iter;

pub(super) mod raw;

use crate::uri::target::{self, Error, Origin, Slash, Target};

/// An admitted relative or origin-form path and optional query.
#[derive(Clone, Copy)]
pub struct Relative<'a> {
    pub(super) value: &'a str,
    pub(super) path_end: u32,
}

impl<'a> Relative<'a> {
    pub(super) fn from_target(target: &'a Target) -> Self {
        Self {
            value: target.path_query(),
            path_end: target.path_end - target.head.end,
        }
    }

    pub fn parse(value: &'a str) -> Result<Self, Error> {
        Ok(Self {
            value,
            path_end: target::path_end(value)?,
        })
    }

    /// Resolves only admitted components; normalization cannot introduce new bytes
    /// other than path separators, so the original grammar proof remains valid.
    /// Materialization precedes offset narrowing.
    pub fn resolve(self, base: &Target) -> Result<Target, Error> {
        if self.value.is_empty() {
            return base.try_clone().map_err(Error::Allocation);
        }
        if self.value.starts_with('/') && !self.has_dots() {
            return base.with_origin(Origin {
                value: self.value,
                path_end: self.path_end,
                slash: Slash::Present,
            });
        }
        target::raw::resolve(self, base)
    }

    pub(super) fn has_dots(self) -> bool {
        target::raw::split(self)
            .0
            .split('/')
            .any(|part| matches!(part, "." | ".."))
    }
}

/// Yields normalized segments from the end without storing or joining them.
/// `prefix` excludes the root slash and ends at a directory separator.
pub(super) fn segments<'a>(
    prefix: &'a str,
    path: &'a str,
) -> impl Iterator<Item = &'a str> + Clone {
    let trailing = matches!(path.rsplit('/').next(), Some("." | ".."));
    let mut parents = 0usize;
    iter::once("").take(usize::from(trailing)).chain(
        path.rsplit('/')
            .chain(prefix.rsplit_terminator('/'))
            .filter(move |part| match *part {
                "." => false,
                ".." => {
                    parents += 1;
                    false
                }
                _ if parents != 0 => {
                    parents -= 1;
                    false
                }
                _ => true,
            }),
    )
}