sark-http 0.39.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::{borrow::Borrow, ops};

use o3::buffer::pool::{self, owners};

use crate::{
    field::scan::Match,
    request::{RangeError, span},
};

/// A query range admitted once against its immutable request storage.
pub struct Entries<'a, const WIRE: bool = false> {
    rest: &'a [u8],
    origin: usize,
}

impl<'a> Entries<'a> {
    pub fn try_new(raw: &'a [u8], range: ops::Range<usize>) -> Result<Self, RangeError> {
        Ok(Self::from_source(raw, RangeError::get(raw, range)?))
    }
}

impl<'a, const WIRE: bool> Entries<'a, WIRE> {
    // All token slices, including empty values, remain subslices of this source.
    fn from_source(source: &[u8], rest: &'a [u8]) -> Self {
        Self {
            rest,
            origin: source.as_ptr().addr(),
        }
    }
}

impl<'a> Entries<'a, true> {
    pub(crate) fn line<P: Borrow<crate::h1::head::line::Parts>>(
        request: &crate::h1::head::line::Request<'a, P>,
    ) -> Option<Self> {
        let span = request.plan().query_span()?;
        let source = request.source();
        // SAFETY: the line or its snapshot preserves the same bytes and compact offsets.
        let rest = unsafe { source.get_unchecked(span.start()..span.end()) };
        Some(Self::from_source(source, rest))
    }

    pub(crate) fn target<S>(
        source: &'a pool::Span<owners::Plain<pool::Layout>, pool::Owned, S>,
        range: ops::Range<usize>,
    ) -> Option<Self> {
        let source = source.as_slice();
        Some(Self::from_source(source, source.get(range)?))
    }

    pub const fn as_bytes(&self) -> &'a [u8] {
        self.rest
    }

    /// The suffix following the byte at the given target offset.
    pub fn after(&self, offset: usize) -> Option<Self> {
        let (_, rest) = self.rest.get(offset..)?.split_first()?;
        Some(Self { rest, ..*self })
    }
}

/// Exact name and value slices retaining their original request offsets.
pub struct Entry<'a, const WIRE: bool = false> {
    name: &'a [u8],
    value: &'a [u8],
    origin: usize,
}

impl<'a, const WIRE: bool> Entry<'a, WIRE> {
    pub const fn name(&self) -> &'a [u8] {
        self.name
    }

    pub fn name_range(&self) -> ops::Range<usize> {
        let start = self.name.as_ptr().addr() - self.origin;
        start..start + self.name.len()
    }

    pub fn try_span(&self) -> Result<span::Span, span::Error> {
        let (value, start) = self.value();
        if WIRE && start < u32::MAX as usize {
            return Ok(span::Span::pack(start, value.len()));
        }
        span::Span::checked(start, value.len())
    }

    pub fn value(&self) -> (&'a [u8], usize) {
        (self.value, self.value.as_ptr().addr() - self.origin)
    }
}

impl<'a, const WIRE: bool> Iterator for Entries<'a, WIRE> {
    type Item = Entry<'a, WIRE>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while !self.rest.is_empty() {
            let (name, value, rest) = match Match::find2(b'=', b'&', self.rest) {
                Some(found) if found.byte() == b'=' => {
                    let tail = found.suffix();
                    let (value, rest) = Match::find(b'&', tail).map_or_else(
                        || tail.split_at(tail.len()),
                        |end| (end.prefix(), end.suffix()),
                    );
                    (found.prefix(), value, rest)
                }
                Some(found) => {
                    let name = found.prefix();
                    let rest = found.suffix();
                    if name.is_empty() {
                        self.rest = rest;
                        continue;
                    }
                    let (_, value) = name.split_at(name.len());
                    (name, value, rest)
                }
                None => {
                    let (name, value) = self.rest.split_at(self.rest.len());
                    (name, value, value)
                }
            };
            self.rest = rest;
            return Some(Entry {
                name,
                value,
                origin: self.origin,
            });
        }
        None
    }
}