sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use o3::alloc::{self, StrExt as _, array};
use std::{mem, ptr};

use crate::uri::target::{
    self, Error, Plan, Relative, Target,
    plan::{Edit, Layout},
    relative,
};

pub(super) fn prefix(t: &Target) -> &str {
    // SAFETY: the stored scheme and its delimiter end at the authority.
    unsafe { t.value.get_unchecked(..t.head.start()) }
}

pub(super) fn authority(t: &Target) -> &str {
    // SAFETY: both authority boundaries belong to this immutable target.
    unsafe { t.value.get_unchecked(t.head.start()..t.head.end as usize) }
}

pub(super) fn host(t: &Target) -> &str {
    // SAFETY: the host lies inside the admitted authority.
    unsafe { t.value.get_unchecked(t.head.start()..t.head.host as usize) }
}

pub(super) fn head(t: &Target) -> &str {
    // SAFETY: the authority ends at this immutable owner's origin.
    unsafe { t.value.get_unchecked(..t.head.end as usize) }
}

pub(super) fn path(t: &Target) -> &str {
    // SAFETY: both ends are admitted ASCII component boundaries.
    unsafe {
        t.value
            .get_unchecked(t.head.end as usize..t.path_end as usize)
    }
}

pub(super) fn origin(t: &Target) -> &str {
    // SAFETY: this immutable owner's origin follows its admitted authority.
    unsafe { t.value.get_unchecked(t.head.end as usize..) }
}

pub(super) fn scheme(t: &Target) -> Option<&str> {
    // SAFETY: the admitted scheme ends at an ASCII boundary in this owner.
    t.head
        .scheme
        .map(|end| unsafe { t.value.get_unchecked(..end.get() as usize) })
}

pub(super) fn port(t: &Target) -> Option<&[u8]> {
    let start = t.head.host as usize;
    let end = t.head.end as usize;
    // SAFETY: the admitted host either ends the authority or precedes its ASCII port separator.
    (start != end).then(|| unsafe { t.value.as_bytes().get_unchecked(start + 1..end) })
}

pub(super) fn query(t: &Target) -> Option<&str> {
    let end = t.path_end as usize;
    // SAFETY: a nonterminal admitted path ends at the ASCII query separator.
    (end != t.value.len()).then(|| unsafe { t.value.get_unchecked(end + 1..) })
}

pub(super) fn clone(value: &str) -> Result<Box<str>, alloc::Exhausted> {
    let value = value.try_to_owned()?;
    // SAFETY: StrExt creates an exact allocation for the copied UTF-8.
    Ok(unsafe { boxed(value) })
}

/// # Safety
/// The offset must be a UTF-8 boundary within the same string.
unsafe fn divide(input: &str, at: usize) -> (&str, &str) {
    // SAFETY: both complementary ranges use the caller's admitted boundary.
    unsafe { (input.get_unchecked(..at), input.get_unchecked(at..)) }
}

pub(super) fn split(input: Relative<'_>) -> (&str, &str) {
    // SAFETY: the path scanner retained a UTF-8 boundary in these same immutable bytes.
    unsafe { divide(input.value, input.path_end as usize) }
}

pub(super) fn directory(t: &Target) -> &str {
    let base = t.path();
    let end = base.rfind('/').unwrap_or(0) + 1;
    // SAFETY: the admitted path starts with a slash, and rfind locates an ASCII separator.
    unsafe { base.get_unchecked(1..end) }
}

pub(super) fn split_authority(input: &str) -> (&str, &str) {
    match input
        .bytes()
        .position(|byte| matches!(byte, b'/' | b'?' | b'#'))
    {
        // SAFETY: all three ASCII delimiters start at UTF-8 boundaries in this input.
        Some(index) => unsafe { divide(input, index) },
        None => (input, ""),
    }
}

/// # Safety
/// The string's length must equal its capacity, retaining its exact global layout.
pub(super) unsafe fn boxed(value: String) -> Box<str> {
    let mut value = mem::ManuallyDrop::new(value);
    let bytes = ptr::slice_from_raw_parts_mut(value.as_mut_ptr(), value.len());
    // SAFETY: the consumed String owns valid UTF-8 in exactly this many bytes;
    // its u8 allocation and Box<str> share the global allocator and layout.
    unsafe { Box::from_raw(bytes as *mut str) }
}

/// # Safety
/// The offset must be an admitted UTF-8 boundary; capacity must cover the resulting bytes.
/// The text must not overlap the destination allocation.
pub(super) unsafe fn insert(value: &mut String, at: usize, text: &str) {
    // SAFETY: admission proves capacity and the UTF-8 split; the overlapping move
    // opens the exact gap before the disjoint text fills it.
    unsafe {
        let bytes = value.as_mut_vec();
        let len = bytes.len();
        let out = bytes.as_mut_ptr();
        out.add(at + text.len()).copy_from(out.add(at), len - at);
        out.add(at)
            .copy_from_nonoverlapping(text.as_ptr(), text.len());
        bytes.set_len(len + text.len());
    }
}

pub(super) fn absolute(value: &str) -> Result<Target, Error> {
    let layout = Layout::parse(value)?;
    // SAFETY: this exact immutable input supplied the entire layout.
    unsafe { copy(layout, value) }.map_err(Error::Allocation)
}

pub(super) struct Parts<'a, const N: usize> {
    source: &'a [&'a str; N],
    len: usize,
}

impl<'a, const N: usize> Parts<'a, N> {
    pub(super) fn new(source: &'a [&'a str; N]) -> Result<Self, Error> {
        let len = source.iter().try_fold(0usize, |sum, part| {
            sum.checked_add(part.len()).ok_or(Error::Length)
        })?;
        Ok(Self { source, len })
    }

    pub(super) fn try_copy(self) -> Result<Box<str>, Error> {
        let plan = array::Plan::try_new(self.len).map_err(|alloc::Overflow| Error::Length)?;
        // SAFETY: the same immutable source supplied the exact output length.
        unsafe { fill(plan, self.source) }.map_err(Error::Allocation)
    }
}

/// # Safety
/// The sum of the parts' lengths must equal the admitted buffer extent.
unsafe fn fill<const N: usize>(
    plan: array::Plan<u8, usize>,
    parts: &[&str; N],
) -> Result<Box<str>, alloc::Exhausted> {
    let len = *plan.extent();
    let mut bytes = plan.try_vec()?;
    let mut out = bytes.as_mut_ptr();
    // SAFETY: every borrowed UTF-8 range fits in the fresh disjoint allocation.
    unsafe {
        for part in parts {
            out.copy_from_nonoverlapping(part.as_ptr(), part.len());
            out = out.add(part.len());
        }
        bytes.set_len(len);
        Ok(boxed(String::from_utf8_unchecked(bytes)))
    }
}

pub(super) fn planned_path(plan: &Plan) -> &str {
    match plan.layout.edit {
        Edit::Slash | Edit::Http => "/",
        Edit::Keep => {
            let range = plan.layout.head.end as usize..plan.layout.path_end as usize;
            // SAFETY: an unedited path retains both boundaries in this immutable input.
            unsafe { plan.value.get_unchecked(range) }
        }
    }
}

pub(super) fn build(plan: Plan) -> Result<Target, alloc::Exhausted> {
    let Plan { mut value, layout } = plan;
    if value.capacity() != *layout.buffer.extent() {
        // SAFETY: Plan owns the unchanged input for this layout.
        return unsafe { copy(layout, &value) };
    }
    // SAFETY: the exact capacity includes all inserted bytes. The authority
    // boundary lies in the input, and both insertions are ASCII.
    unsafe {
        match layout.edit {
            Edit::Keep => {}
            Edit::Slash => insert(&mut value, layout.head.end as usize, "/"),
            Edit::Http => {
                insert(&mut value, 0, "http://");
                insert(&mut value, layout.head.end as usize, "/");
            }
        }
        Ok(Target {
            value: boxed(value),
            head: layout.head,
            path_end: layout.path_end,
        })
    }
}

/// # Safety
/// The input must be the same bytes used to admit this layout.
unsafe fn copy(layout: Layout, value: &str) -> Result<Target, alloc::Exhausted> {
    // SAFETY: each set of parts emits the exact length admitted for this input.
    let output = unsafe {
        match layout.edit {
            Edit::Keep => fill(layout.buffer, &[value]),
            Edit::Slash => {
                let (head, tail) = divide(value, layout.head.end as usize);
                fill(layout.buffer, &[head, "/", tail])
            }
            Edit::Http => fill(layout.buffer, &["http://", value, "/"]),
        }
    }?;
    Ok(Target {
        value: output,
        head: layout.head,
        path_end: layout.path_end,
    })
}

pub(super) fn resolve(input: Relative<'_>, base: &Target) -> Result<Target, Error> {
    let (path, query) = split(input);
    let (value, path_end) = if path.is_empty() {
        // SAFETY: the base owns this admitted UTF-8 prefix through its path.
        let prefix = unsafe { base.value.get_unchecked(..base.path_end as usize) };
        let value = Parts::new(&[prefix, query])?.try_copy()?;
        (value, base.path_end)
    } else {
        let (prefix, path) = match path.strip_prefix('/') {
            Some(path) => ("", path),
            None => (directory(base), path),
        };
        let segments = relative::segments(prefix, path);
        let path_len = segments.clone().try_fold(0usize, |len, part| {
            len.checked_add(part.len() + 1).ok_or(Error::Length)
        })?;
        let path_end = (base.head.end as usize)
            .checked_add(path_len)
            .ok_or(Error::Length)?;
        let capacity = path_end.checked_add(query.len()).ok_or(Error::Length)?;
        let buffer = array::Plan::try_new(capacity).map_err(|alloc::Overflow| Error::Length)?;
        // SAFETY: the clone measured this same deterministic iterator over
        // immutable segments, including one preceding slash per segment.
        let value =
            unsafe { relative::raw::normalize(buffer, head(base), path_len, segments, query) }
                .map_err(Error::Allocation)?;
        target::narrow(path_len)?;
        let path_end = target::narrow(path_end)?;
        (value, path_end)
    };
    Ok(Target {
        value,
        head: base.head,
        path_end,
    })
}