sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::{
    borrow::BorrowMut,
    iter::FusedIterator,
    ops::{ControlFlow, Range},
};

use crate::{
    payload::{owned, response::Destination},
    request::Id,
};
use o3::buffer::{
    self, hold,
    resident::{self, bound},
    segments, storage,
    write::{self, Sink as _},
};

mod sources;
mod store;
use sources::{Admit, Sealed};
pub(super) use store::Store;

/// Statically dispatched response payload.
pub trait Body<'d, Ranges: Copy + 'd = ()>: Sized + Sealed {
    type Bound: bound::Bound + 'd;
    type Storage: Store<'d, Ranges, Self>;
    type Prepared: Into<Option<Self::Storage>>;

    #[doc(hidden)]
    const INLINE: bool = false;

    fn len(&self) -> usize;

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn as_slice(&self) -> Option<&[u8]>;

    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
        self.as_slice()
            .filter(|body| !<[u8]>::is_empty(body))
            .into_iter()
    }

    #[doc(hidden)]
    fn try_prepare(self) -> Result<Self::Prepared, owned::Error>;

    #[doc(hidden)]
    fn try_inline<L: BorrowMut<usize>>(
        self,
        _: &mut write::raw::Slice<'_, L>,
    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
        <Self as Body<'d, Ranges>>::try_prepare(self).map(ControlFlow::Continue)
    }

    #[doc(hidden)]
    fn store<'place, const DEFERRED_FIXED: bool, S, D: Destination<'place, 'd, S, Ranges>>(
        body: Self::Prepared,
        place: D::Place,
        current: Option<Id<'d>>,
    ) -> D::Stored {
        match body.into() {
            Some(owner) => {
                <Self::Storage as Store<'d, Ranges, Self>>::place::<DEFERRED_FIXED, S, D>(
                    owner, place, current,
                )
            }
            None => D::empty(place),
        }
    }
}

impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for [u8; 0] {
    type Bound = bound::AtMost<0>;
    type Storage = Self;
    type Prepared = Self;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        0
    }
    fn as_slice(&self) -> Option<&[u8]> {
        Some(self)
    }
    fn try_prepare(self) -> Result<Self, owned::Error> {
        Ok(self)
    }
}

impl<'d, Ranges: Copy + 'd, T> Body<'d, Ranges> for T
where
    T: buffer::raw::Source,
    storage::NonEmpty<T>: Admit + Store<'d, Ranges, T>,
{
    type Bound = bound::Unbounded;
    type Storage = storage::NonEmpty<T>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = <Self::Storage as Admit>::CAN_INLINE;

    fn len(&self) -> usize {
        self.as_ref().len()
    }

    fn as_slice(&self) -> Option<&[u8]> {
        Some(self.as_ref())
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        Ok(storage::NonEmpty::try_new(self).ok())
    }
}

impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for storage::NonEmpty<Vec<u8>> {
    type Bound = bound::Unbounded;
    type Storage = Self;
    type Prepared = Self;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        self.as_ref().len()
    }
    fn is_empty(&self) -> bool {
        false
    }
    fn as_slice(&self) -> Option<&[u8]> {
        Some(self.as_ref())
    }
    fn try_prepare(self) -> Result<Self, owned::Error> {
        Ok(self)
    }
}

impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for String {
    type Bound = bound::Unbounded;
    type Storage = storage::NonEmpty<Vec<u8>>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        String::len(self)
    }
    fn as_slice(&self) -> Option<&[u8]> {
        Some(self.as_bytes())
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        <Vec<u8> as Body<'d, Ranges>>::try_prepare(self.into_bytes())
    }
}

fn copy(bytes: &[u8]) -> Result<Option<storage::NonEmpty<storage::Shared>>, storage::AllocError> {
    storage::NonEmpty::try_new(bytes)
        .ok()
        .map(storage::NonEmpty::<storage::Shared>::try_from)
        .transpose()
}

impl<'d, Ranges: Copy + 'd, T: AsRef<[u8]> + ?Sized> Body<'d, Ranges> for &T
where
    Self: Sealed,
{
    type Bound = bound::Unbounded;
    type Storage = storage::NonEmpty<storage::Shared>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        self.as_ref().len()
    }
    fn as_slice(&self) -> Option<&[u8]> {
        Some(self.as_ref())
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        copy(self.as_ref()).map_err(owned::Error::Storage)
    }

    fn try_inline<L: BorrowMut<usize>>(
        self,
        out: &mut write::raw::Slice<'_, L>,
    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
        let bytes = match storage::NonEmpty::try_new(self.as_ref()) {
            Ok(bytes) => bytes,
            Err(_) => return Ok(ControlFlow::Continue(None)),
        };
        if out.write_slice(bytes.as_ref()).is_ok() {
            return Ok(ControlFlow::Break(bytes.len().get()));
        }
        storage::NonEmpty::<storage::Shared>::try_from(bytes)
            .map(|body| ControlFlow::Continue(Some(body)))
            .map_err(owned::Error::Storage)
    }
}

impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for &mut &[u8] {
    type Bound = bound::Unbounded;
    type Storage = storage::NonEmpty<storage::Shared>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        (**self).len()
    }

    fn as_slice(&self) -> Option<&[u8]> {
        Some(**self)
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        copy(self)
            .map_err(storage::BuildError::from)
            .map_err(owned::Error::Build)
    }

    fn try_inline<L: BorrowMut<usize>>(
        self,
        out: &mut write::raw::Slice<'_, L>,
    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
        let bytes = *self;
        if out.write_slice(bytes).is_ok() {
            return Ok(ControlFlow::Break(bytes.len()));
        }
        <Self as Body<'d, Ranges>>::try_prepare(self).map(ControlFlow::Continue)
    }
}

impl<'d, 'input, 'ranges, 'bytes, Ranges: Copy + 'd, N: buffer::raw::Length> Body<'d, Ranges>
    for &'input mut hold::raw::Set<'ranges, &'bytes [u8], N>
{
    type Bound = bound::Unbounded;
    type Storage = storage::NonEmpty<storage::Shared>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        hold::raw::Set::len(&**self)
    }

    fn as_slice(&self) -> Option<&[u8]> {
        self.contiguous()
    }

    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
        hold::raw::Set::iter(&**self)
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        hold::raw::Set::try_copy(self)
            .map_err(storage::BuildError::from)
            .map_err(owned::Error::Build)
    }

    fn try_inline<L: BorrowMut<usize>>(
        self,
        out: &mut write::raw::Slice<'_, L>,
    ) -> Result<ControlFlow<usize, Self::Prepared>, owned::Error> {
        if let Some(bytes) = self.contiguous()
            && out.write_slice(bytes).is_ok()
        {
            return Ok(ControlFlow::Break(bytes.len()));
        }
        <Self as Body<'d, Ranges>>::try_prepare(self).map(ControlFlow::Continue)
    }
}

impl<'d, Ranges: Copy + 'd> Body<'d, Ranges> for segments::raw::Data<'d, (), Ranges> {
    type Bound = bound::Unbounded;
    type Storage = Self;
    type Prepared = Self;

    fn len(&self) -> usize {
        segments::raw::Data::len(self).get()
    }
    fn is_empty(&self) -> bool {
        false
    }
    fn as_slice(&self) -> Option<&[u8]> {
        segments::raw::Data::contiguous(self)
    }

    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
        segments::raw::Iter::from(self)
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        Ok(self)
    }
}

impl<'d, Inline: Copy, Ranges: Copy + 'd> Body<'d, Ranges>
    for &mut Option<segments::raw::Data<'d, Inline, Ranges>>
{
    type Bound = bound::Unbounded;
    type Storage = Self;
    type Prepared = Self;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        self.as_ref().map_or(0, |body| body.len().get())
    }
    fn is_empty(&self) -> bool {
        self.is_none()
    }
    fn as_slice(&self) -> Option<&[u8]> {
        match self {
            Some(body) => body.contiguous(),
            None => Some(&[]),
        }
    }

    fn segments(&self) -> impl FusedIterator<Item: AsRef<[u8]>> {
        self.iter().flat_map(IntoIterator::into_iter)
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        Ok(self)
    }
}

impl<'input, 'd, Ranges: Copy + 'd> Body<'d, Ranges> for segments::raw::View<'input, 'd, Ranges> {
    type Bound = bound::Unbounded;
    type Storage = segments::raw::Part<'d, Ranges>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        segments::raw::View::len(self)
    }
    fn as_slice(&self) -> Option<&[u8]> {
        Some(self.as_ref())
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        self.try_project().map_err(owned::Error::Retain)
    }
}

impl<'d, Ranges: Copy + 'd> Body<'d, Ranges>
    for buffer::raw::Input<&mut storage::Shared<resident::State<'d>>, Range<usize>>
{
    type Bound = bound::Unbounded;
    type Storage = storage::NonEmpty<storage::Shared<resident::State<'d>>>;
    type Prepared = Option<Self::Storage>;

    const INLINE: bool = true;

    fn len(&self) -> usize {
        let bounds = self.as_parts().1;
        bounds.end - bounds.start
    }
    fn as_slice(&self) -> Option<&[u8]> {
        Some(self.as_ref())
    }

    fn try_prepare(self) -> Result<Self::Prepared, owned::Error> {
        self.try_project().map_err(owned::Error::Retain)
    }
}