sark-http 0.39.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::mem;

use map::{Owned, record::Entry};
use o3::{
    alloc,
    buffer::{bytes::scope, pool, pool::owners, storage::Shared, write},
};
use packed::{Iter, RangeIter, prefix::Prefix};
use write::{SpareExt as _, edit, spans};

use crate::field::metadata::{self, lower::plain::Error, map, packed, section::storage};

#[derive(Debug)]
#[repr(transparent)]
pub struct Decoded<S = pool::Span, const PREFIX: usize = 0> {
    storage: S,
}

impl Decoded {
    /// Validates arbitrary storage once before exposing infallible iteration.
    pub fn try_from(storage: pool::Span) -> Result<Self, storage::Fault> {
        Ok(<Self as storage::Block>::from(storage::Finished::try_from(
            storage,
        )?))
    }
}

impl<const PREFIX: usize> Decoded<pool::Span, PREFIX> {
    pub fn target(
        &self,
        range: std::ops::Range<usize>,
    ) -> Option<crate::request::query::Entries<'_, true>> {
        crate::request::query::Entries::target(&self.storage, range)
    }

    pub fn freeze(self) -> Decoded<storage::Bytes, PREFIX> {
        Decoded {
            storage: storage::Bytes::new(self.storage.freeze()),
        }
    }

    /// Consumes the record proof and returns its exclusively owned storage.
    pub fn into_lease(self) -> pool::Span {
        self.storage
    }
}

impl<const PREFIX: usize> From<Decoded<pool::Span, PREFIX>> for Shared {
    fn from(value: Decoded<pool::Span, PREFIX>) -> Self {
        value.storage.freeze().into_shared()
    }
}

impl<S: AsRef<[u8]>, const PREFIX: usize> Decoded<S, PREFIX> {
    pub fn borrow(&self) -> Decoded<&[u8], PREFIX> {
        Decoded {
            storage: self.storage.as_ref(),
        }
    }

    pub fn iter(&self) -> Iter<'_> {
        // SAFETY: Finished admits PREFIX bytes; frozen and scoped owners preserve
        // that extent without exposing mutable storage.
        Iter::new(unsafe { self.storage.as_ref().get_unchecked(PREFIX..) })
    }

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

    pub fn is_empty(&self) -> bool {
        self.storage.as_ref().len() == PREFIX
    }

    pub fn get(&self, name: &[u8]) -> Option<&[u8]> {
        self.iter()
            .find(|field| field.name == name)
            .map(|field| field.value)
    }

    pub fn as_bytes(&self) -> &[u8] {
        self.storage.as_ref()
    }

    pub fn ranges(&self) -> RangeIter<'_> {
        RangeIter::new(self.iter(), PREFIX)
    }

    pub fn try_to_owned(&self) -> Result<Vec<Owned>, alloc::Error> {
        let mut fields = Vec::new();
        for field in self.iter() {
            alloc::try_vacant(&mut fields)?.insert(Owned::try_from(field)?);
        }
        Ok(fields)
    }
}

impl<const PREFIX: usize> Decoded<storage::Bytes, PREFIX> {
    pub fn retain(self) -> Decoded<Shared, PREFIX> {
        Decoded {
            storage: self.storage.into(),
        }
    }
}

impl<S: storage::Scope, const PREFIX: usize> storage::Scope for Decoded<S, PREFIX> {
    type Scoped<'id> = Decoded<S::Scoped<'id>, PREFIX>;

    fn bind<'id>(self, identity: scope::Owner<'id, ()>) -> Self::Scoped<'id> {
        Decoded {
            storage: S::bind(self.storage, identity),
        }
    }

    fn unbind<'id>(head: Self::Scoped<'id>) -> Self {
        Decoded {
            storage: S::unbind(head.storage),
        }
    }

    fn source<'req, 'id: 'req>(
        head: &'req Self::Scoped<'id>,
    ) -> scope::View<'req, 'id> {
        S::source(&head.storage)
    }
}

impl<'id, S: Into<scope::Owner<'id, Shared>>, const PREFIX: usize>
    From<Decoded<S, PREFIX>> for scope::Owner<'id, Shared>
{
    fn from(head: Decoded<S, PREFIX>) -> Self {
        head.storage.into()
    }
}

impl<const PREFIX: usize> metadata::Metadata for Decoded<pool::Span, PREFIX> {
    type Iter<'a> = Iter<'a>;

    fn fields(&self) -> Self::Iter<'_> {
        self.iter()
    }
}

impl<const PREFIX: usize> storage::Block for Decoded<pool::Span, PREFIX> {
    type Format = storage::Raw;
    const PREFIX: &'static [u8] = &[0; PREFIX];

    fn from(storage: storage::Finished<Self>) -> Self {
        Self {
            storage: storage.into_lease(),
        }
    }

    fn into_bytes(self) -> storage::Bytes {
        storage::Bytes::new(self.storage.freeze())
    }
}

impl<S: AsRef<[u8]>, const PREFIX: usize> AsRef<[u8]> for Decoded<S, PREFIX> {
    fn as_ref(&self) -> &[u8] {
        self.storage.as_ref()
    }
}

impl<const PREFIX: usize> PartialEq for Decoded<pool::Span, PREFIX> {
    fn eq(&self, other: &Self) -> bool {
        self.storage.as_ref() == other.storage.as_ref()
    }
}

impl<const PREFIX: usize> Eq for Decoded<pool::Span, PREFIX> {}

impl<'a, const PREFIX: usize> IntoIterator for &'a Decoded<pool::Span, PREFIX> {
    type Item = Entry<'a>;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

const _: () = assert!(
    mem::size_of::<Decoded>()
        == mem::size_of::<pool::Span<owners::Plain<pool::Layout>, pool::Owned, pool::Frozen>>()
);
const _: () = assert!(mem::size_of::<Option<Decoded>>() == mem::size_of::<Decoded>());

pub struct Record<'a> {
    output: edit::Edit<'a, { Prefix::LEN }>,
}

impl<const PREFIX: usize> storage::Writer<Decoded<pool::Span, PREFIX>> {
    pub fn try_field(&mut self) -> Result<Record<'_>, Error> {
        let output =
            edit::Edit::try_new(self.lease.spare(), &[0; Prefix::LEN]).map_err(Error::Write)?;
        Ok(Record { output })
    }
}

impl<'a> Record<'a> {
    pub fn payload(&mut self) -> spans::Writer<'_, 'a> {
        self.output.bounded()
    }

    pub fn finish(mut self, name: usize, indexing: crate::field::Indexing) -> Result<(), Error> {
        let payload = self.output.len() - Prefix::LEN;
        let value = payload
            .checked_sub(name)
            .ok_or(Error::Layout([0, name, payload]))?;
        *self.output.prefix() = Prefix::try_new(name, value, indexing)?.to_bytes();
        self.output.commit();
        Ok(())
    }
}