sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
//! Lossless absolute-URI and client-target proofs.

use std::{fmt, num, str};

use o3::alloc;

use crate::uri::{self, path};

mod plan;
pub use plan::Plan;
mod raw;
mod relative;
pub use relative::Relative;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    Colon,
    Scheme(uri::Error),
    Separator { colon: usize, len: usize },
    UserInfo,
    Authority(uri::Error),
    Start { byte: Option<u8> },
    Origin(path::Error),
    Length,
    Index { value: usize },
    Allocation(alloc::Exhausted),
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Absolute<'a> {
    scheme: &'a str,
    parsed: uri::Authority<'a>,
    origin: Origin<'a>,
}

impl<'a> Absolute<'a> {
    pub fn parse(value: &'a str) -> Result<Self, Error> {
        let (scheme, rest) = value.split_once(':').ok_or(Error::Colon)?;
        uri::Scheme::validate(scheme.as_bytes()).map_err(Error::Scheme)?;
        let rest = rest.strip_prefix("//").ok_or(Error::Separator {
            colon: scheme.len(),
            len: value.len(),
        })?;
        let (raw, tail) = raw::split_authority(rest);
        let parsed = authority(raw)?;
        let origin = Origin::from_uri(tail)?;
        Ok(Self {
            scheme,
            parsed,
            origin,
        })
    }

    pub const fn scheme(self) -> &'a str {
        self.scheme
    }

    pub const fn authority(self) -> uri::Authority<'a> {
        self.parsed
    }

    pub const fn origin(self) -> Origin<'a> {
        self.origin
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Origin<'a> {
    value: &'a str,
    path_end: u32,
    slash: Slash,
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
enum Slash {
    Present,
    Insert,
}

impl<'a> Origin<'a> {
    pub const ROOT: Self = Self {
        value: "/",
        path_end: 1,
        slash: Slash::Present,
    };

    pub fn parse(value: &'a str) -> Result<Self, Error> {
        if !value.starts_with('/') {
            return Err(Error::Start {
                byte: value.as_bytes().first().copied(),
            });
        }
        Self::validated(value, Slash::Present)
    }

    fn from_uri(value: &'a str) -> Result<Self, Error> {
        match value.as_bytes().first() {
            Some(b'/') => Self::validated(value, Slash::Present),
            Some(b'?') => Self::validated(value, Slash::Insert),
            Some(byte) => Err(Error::Start { byte: Some(*byte) }),
            None => Self::validated(value, Slash::Insert),
        }
    }

    fn validated(value: &'a str, slash: Slash) -> Result<Self, Error> {
        Ok(Self {
            value,
            path_end: path_end(value)?,
            slash,
        })
    }

    fn prefix(self) -> &'a str {
        match self.slash {
            Slash::Present => "",
            Slash::Insert => "/",
        }
    }

    fn path_end(self) -> usize {
        self.path_end as usize + usize::from(self.slash == Slash::Insert)
    }
}

impl<'a> From<&'a Target> for Origin<'a> {
    fn from(target: &'a Target) -> Self {
        let relative = Relative::from_target(target);
        Self {
            value: relative.value,
            path_end: relative.path_end,
            slash: Slash::Present,
        }
    }
}

fn authority(raw: &str) -> Result<uri::Authority<'_>, Error> {
    if raw.as_bytes().contains(&b'@') {
        return Err(Error::UserInfo);
    }
    uri::Authority::parse(raw.as_bytes()).map_err(Error::Authority)
}

fn path_end(value: &str) -> Result<u32, Error> {
    let scan = path::Scan::new(value.as_bytes())
        .complete()
        .map_err(Error::Origin)?;
    narrow(scan.path_end())
}

fn narrow(value: usize) -> Result<u32, Error> {
    if value > u32::MAX as usize {
        return Err(Error::Index { value });
    }
    Ok(value as u32)
}

#[derive(Clone, Copy, Debug)]
struct Head {
    scheme: Option<num::NonZero<u32>>,
    host: u32,
    end: u32,
}

impl Head {
    fn new(scheme: Option<num::NonZero<u32>>, host: usize, end: usize) -> Result<Self, Error> {
        Ok(Self {
            scheme,
            host: narrow(host)?,
            end: narrow(end)?,
        })
    }

    fn start(self) -> usize {
        self.scheme.map_or(0, |end| end.get() as usize + 3)
    }
}

/// An owned URI target with one admitted authority and origin form.
///
/// Component offsets retain the parser's bounds and grammar proofs. [`Self::try_clone`]
/// copies the owned bytes; targets never share reference-counted storage.
#[derive(Debug)]
pub struct Target {
    value: Box<str>,
    head: Head,
    path_end: u32,
}

impl Target {
    pub fn parse(value: &str) -> Result<Self, Error> {
        raw::absolute(value)
    }

    pub fn new(raw: &str, origin: Origin<'_>) -> Result<Self, Error> {
        let host = authority(raw)?.host().len();
        let head = Head::new(None, host, raw.len())?;
        Self::join(head, "", raw, origin)
    }

    pub fn from_host(
        host: &str,
        port: Option<num::NonZero<u16>>,
        origin: Origin<'_>,
    ) -> Result<Self, Error> {
        let brackets = !host.starts_with('[') && host.contains(':');
        let length = host.len() + usize::from(brackets) * 2;
        let host_end = if brackets {
            if !uri::Authority::is_ip(host.as_bytes()) {
                return Err(Error::Authority(uri::Error::InvalidHost));
            }
            length
        } else {
            if host.is_empty() && port.is_some() {
                return Err(Error::Authority(uri::Error::InvalidHost));
            }
            let len = uri::host_end(host.as_bytes()).map_err(Error::Authority)?;
            if port.is_some() && len != host.len() {
                return Err(Error::Authority(uri::Error::InvalidPort));
            }
            len
        };
        let mut digits = fmt::NumBuffer::new();
        let port = port.map(|port| port.get().format_into(&mut digits));
        let end = length + port.map_or(0, |port| port.len() + 1);
        let (left, right) = if brackets { ("[", "]") } else { ("", "") };
        let sep = if port.is_some() { ":" } else { "" };
        let bytes = [
            left,
            host,
            right,
            sep,
            port.unwrap_or_default(),
            origin.prefix(),
            origin.value,
        ];
        let output = raw::Parts::new(&bytes)?;
        let path_end = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
        let head = Head::new(None, host_end, end)?;
        let path_end = narrow(path_end)?;
        let value = output.try_copy()?;
        Ok(Self {
            value,
            head,
            path_end,
        })
    }

    pub fn scheme_str(&self) -> Option<&str> {
        raw::scheme(self)
    }

    /// Copies the admitted bytes and offsets without parsing again.
    pub fn try_clone(&self) -> Result<Self, alloc::Exhausted> {
        Ok(Self {
            value: raw::clone(&self.value)?,
            head: self.head,
            path_end: self.path_end,
        })
    }

    pub fn authority(&self) -> &str {
        raw::authority(self)
    }

    /// The host spelling in the authority, including IPv6 brackets.
    pub fn host_raw(&self) -> &str {
        raw::host(self)
    }

    pub fn host(&self) -> &str {
        let host = self.host_raw();
        host.strip_prefix('[')
            .and_then(|host| host.strip_suffix(']'))
            .unwrap_or(host)
    }

    pub fn path(&self) -> &str {
        raw::path(self)
    }

    pub fn path_query(&self) -> &str {
        raw::origin(self)
    }

    pub fn query(&self) -> Option<&str> {
        raw::query(self)
    }

    pub fn retarget(self, raw: &str) -> Result<Self, Error> {
        let parsed = authority(raw)?;
        let start = self.head.start();
        let head = Head::new(
            self.head.scheme,
            start + parsed.host().len(),
            start + raw.len(),
        )?;
        Self::join(head, raw::prefix(&self), raw, Origin::from(&self))
    }

    pub fn with_origin(&self, origin: Origin<'_>) -> Result<Self, Error> {
        Self::join(self.head, raw::head(self), "", origin)
    }

    fn join(head: Head, prefix: &str, raw: &str, origin: Origin<'_>) -> Result<Self, Error> {
        let end = head.end as usize;
        let bytes = [prefix, raw, origin.prefix(), origin.value];
        let output = raw::Parts::new(&bytes)?;
        let path_end = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
        let path_end = narrow(path_end)?;
        let value = output.try_copy()?;
        Ok(Self {
            value,
            head,
            path_end,
        })
    }

    /// Removes dot segments while retaining the admitted component syntax.
    pub fn normalize(self) -> Result<Self, Error> {
        let relative = Relative::from_target(&self);
        if !relative.has_dots() {
            return Ok(self);
        }
        raw::resolve(relative, &self)
    }

    /// Borrows the authority components proved when this target was admitted.
    pub fn parts(&self) -> uri::Authority<'_> {
        let host = self.host_raw().as_bytes();
        let port = raw::port(self);
        uri::Authority::new(host, port)
    }
}

impl AsRef<str> for Target {
    fn as_ref(&self) -> &str {
        &self.value
    }
}

impl str::FromStr for Target {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if !value.contains("://") {
            return Self::new(value, Origin::ROOT);
        }
        Self::parse(value)
    }
}

impl PartialEq for Target {
    fn eq(&self, other: &Self) -> bool {
        let scheme = match (self.scheme_str(), other.scheme_str()) {
            (Some(left), Some(right)) => left.eq_ignore_ascii_case(right),
            (None, None) => true,
            _ => false,
        };
        scheme
            && self.authority().eq_ignore_ascii_case(other.authority())
            && self.path_query() == other.path_query()
    }
}

impl Eq for Target {}

const _: () = assert!(core::mem::size_of::<Absolute<'_>>() <= 9 * core::mem::size_of::<usize>());
const _: () = assert!(core::mem::size_of::<Slash>() == core::mem::size_of::<bool>());
const _: () = assert!(core::mem::size_of::<Origin<'_>>() <= 3 * core::mem::size_of::<usize>());
const _: () = assert!(core::mem::size_of::<Target>() <= 4 * core::mem::size_of::<usize>());