sark-http 0.39.0

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

use o3::buffer::{
    bytes::scope,
    hold::ranges,
    segments::{self, Source}, storage,
    write::{Sink as _, SpareExt as _},
};

use crate::{
    owner::{handoff, handoff::stage},
    payload::{
        owned,
        response,
    },
};

pub mod iter;
mod retained;
mod view;

#[doc(hidden)]
pub use retained::Retained;
pub use view::View;

#[derive(Clone, Copy, Debug)]
enum RefStorage<'req, 'd> {
    Discarded,
    Empty(&'req [u8]),
    /// One nonempty slice, admitted by `Ref::from_slice`.
    Slice(&'req [u8]),
    Retained(Retained<'req, 'd>),
    Ranges(&'req ranges::Set<'req, &'req [u8]>),
}

/// Borrowed logical body preserving transport segmentation.
#[derive(Clone, Copy, Debug)]
pub struct Ref<'req, 'd> {
    storage: RefStorage<'req, 'd>,
    len: usize,
}

impl<'req, 'd> Ref<'req, 'd> {
    /// Classifies an empty view or one nonempty borrowed segment.
    pub const fn from_slice(bytes: &'req [u8]) -> Self {
        let storage = if bytes.is_empty() {
            RefStorage::Empty(bytes)
        } else {
            RefStorage::Slice(bytes)
        };
        Self {
            storage,
            len: bytes.len(),
        }
    }

    #[doc(hidden)]
    pub const fn discarded(len: usize) -> Self {
        Self {
            storage: RefStorage::Discarded,
            len,
        }
    }

    #[doc(hidden)]
    pub const fn from_ranges(ranges: &'req ranges::Set<'req, &'req [u8]>) -> Self {
        Self {
            storage: RefStorage::Ranges(ranges),
            len: ranges.len(),
        }
    }

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

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

    pub fn count(&self) -> segments::Count {
        match self.storage {
            RefStorage::Discarded | RefStorage::Empty(_) => segments::Count::EMPTY,
            RefStorage::Slice(_) => segments::Count::ONE,
            RefStorage::Retained(body) => body.count(),
            RefStorage::Ranges(ranges) => ranges.count(),
        }
    }

    pub fn segment(&self, index: usize) -> Option<&'req [u8]> {
        match self.storage {
            RefStorage::Discarded | RefStorage::Empty(_) => None,
            RefStorage::Slice(bytes) => (index == 0).then_some(bytes),
            RefStorage::Retained(body) => body.segment(index),
            RefStorage::Ranges(ranges) => ranges.get(index).map(|view| view.as_slice()),
        }
    }

    pub fn segments(self) -> iter::Slices<'req, 'd> {
        iter::Slices::new(self)
    }

    pub fn as_slice(&self) -> Option<&'req [u8]> {
        match self.storage {
            RefStorage::Discarded => None,
            RefStorage::Empty(bytes) => Some(bytes),
            RefStorage::Slice(bytes) => Some(bytes),
            RefStorage::Retained(body) => body.as_slice(),
            RefStorage::Ranges(ranges) => ranges.contiguous(),
        }
    }

    /// Copies the logical body into one exact shared owner.
    pub fn try_copy(self) -> Result<storage::Shared, owned::Error> {
        if let RefStorage::Discarded = self.storage {
            return Err(owned::Error::Discarded);
        }
        let mut owner = storage::Owned::try_with(self.len())
            .map_err(storage::BuildError::from)
            .map_err(owned::Error::Build)?;
        let mut out = owner.spare();
        for part in self.segments() {
            out.write_slice(part)
                .map_err(storage::BuildError::Build)
                .map_err(owned::Error::Build)?;
        }
        out.commit();
        Ok(owner.freeze())
    }

    pub(crate) const fn try_retained(self) -> Result<Retained<'req, 'd>, Self> {
        match self.storage {
            RefStorage::Retained(body) => Ok(body),
            _ => Err(self),
        }
    }
}

impl<'src, 'd> response::Body<'d> for Ref<'src, 'd> {
    type Bound = o3::buffer::resident::bound::Unbounded;
    type Selected<S, B> = handoff::Selection<'d, S, B>;

    const INLINE: bool = true;

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

    fn as_slice(&self) -> Option<&[u8]> {
        Self::as_slice(self)
    }

    fn segments(&self) -> impl Iterator<Item = &[u8]> + FusedIterator {
        iter::Slices::new(*self)
    }

    fn try_resolve<'req, H: scope::Source, O: stage::Body<'req, 'd>>(
        self,
        slot: &handoff::Slot<'req, 'd, H, O>,
    ) -> Result<Self::Selected<H::Selection, O>, owned::Error> {
        handoff::Selection::try_view(slot, self)
    }

    fn try_resolve_into<
        'req,
        H: scope::Source,
        O: stage::Body<'req, 'd>,
        L: std::borrow::BorrowMut<usize>,
    >(
        self,
        slot: &handoff::Slot<'req, 'd, H, O>,
        out: &mut o3::buffer::write::Slice<'_, L>,
    ) -> Result<ControlFlow<usize, handoff::Selection<'d, H::Selection, O>>, owned::Error> {
        if matches!(self.storage, RefStorage::Slice(_) | RefStorage::Ranges(_))
            && let Some(bytes) = self.as_slice()
            && let Some(written) = handoff::copy::into(out, bytes)
        {
            return Ok(ControlFlow::Break(written));
        }
        self.try_resolve(slot).map(ControlFlow::Continue)
    }
}

const _: () = {
    assert!(core::mem::size_of::<Ref<'static, 'static>>() == 4 * core::mem::size_of::<usize>());
};

impl<'req, 'd> From<&'req Source<'d>> for Ref<'req, 'd> {
    fn from(body: &'req Source<'d>) -> Self {
        Self {
            storage: RefStorage::Retained(Retained::Segments(body)),
            len: body.len(),
        }
    }
}