sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::{borrow::BorrowMut, convert::Infallible};

use o3::buffer::{
    storage,
    write::{self, consume},
};

use super::{Encode, bounded, exact};

pub fn write<const EXACT: bool, B: Encode, L: BorrowMut<usize>>(
    body: B,
    mut target: write::raw::Slice<'_, L>,
) -> Result<usize, storage::BuildError<consume::Error>> {
    body.encode(&mut target)
        .map_err(storage::BuildError::Build)?;
    let written = target.len();
    if EXACT {
        target.try_complete().map_err(storage::BuildError::Length)?;
    }
    Ok(written)
}

pub fn build<B: Encode, T: TryFrom<storage::Owned>>(
    body: B,
    limit: usize,
) -> Result<T, storage::BuildError<consume::Error>>
where
    T::Error: Into<consume::Error>,
{
    let mut owner = storage::Owned::try_with(limit)?;
    body.encode(&mut write::raw::Slice::from(&mut owner))
        .map_err(storage::BuildError::Build)?;
    match T::try_from(owner) {
        Ok(owner) => Ok(owner),
        Err(error) => Err(storage::BuildError::Length(error.into())),
    }
}

/// Deferred declarations are measured only if the transport accepts a body.
pub trait Source<const EXACT: bool>: Encode {
    type Error: Into<exact::Overflow>;

    fn try_limit(&self) -> Result<usize, Self::Error>;
}

impl<B: exact::TryBody> Source<true> for B {
    type Error = exact::Overflow;

    fn try_limit(&self) -> Result<usize, Self::Error> {
        self.try_len()
    }
}

impl<B: bounded::Body> Source<false> for B {
    type Error = Infallible;

    fn try_limit(&self) -> Result<usize, Self::Error> {
        Ok(self.max_len())
    }
}