sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use core::{mem, num::NonZero, ops::ControlFlow};

use o3::{
    buffer::{
        resident,
        storage::Owned,
        write::{Sink as _, SpareExt as _, consume},
    },
    mem::Rejected,
};

use crate::{
    field,
    h1::{
        chunk::{Error, Framer, Framing, Run, scan::state},
        field::Entry,
    },
};

#[derive(Clone, Copy)]
pub struct Cursor {
    pub(super) state: state::State,
    pub(super) wire: usize,
}

pub(super) enum Progress {
    More {
        next: Cursor,
        consumed: Option<NonZero<usize>>,
    },
    Complete {
        wire: usize,
        consumed: NonZero<usize>,
        trailers: NonZero<u32>,
    },
}

/// The current input's exact admitted trailer prefix and its continuation.
pub struct Pending<'input> {
    pub(super) bytes: &'input [u8],
    pub(super) consumed: NonZero<usize>,
    pub(super) cursor: Cursor,
}

impl Cursor {
    pub(super) fn scan<'a>(
        &self,
        input: &'a [u8],
        limits: &Framing,
    ) -> Result<(Progress, &'a [u8]), Error> {
        let mut cursor = *self;
        for (offset, &byte) in input.iter().enumerate() {
            let wire = Framer::wire(cursor.wire, 1, limits)?;
            let progress = cursor.state.scan(byte, cursor.wire, limits)?;
            cursor.wire = wire;
            match progress {
                ControlFlow::Continue(state) => cursor.state = state,
                ControlFlow::Break(trailers) => {
                    let next = NonZero::<usize>::MIN.saturating_add(offset);
                    return Ok((
                        Progress::Complete {
                            wire,
                            consumed: next,
                            trailers,
                        },
                        Run::complete(input, next.get()).into_slice(),
                    ));
                }
            }
        }
        Ok((
            Progress::More {
                next: cursor,
                consumed: NonZero::new(input.len()),
            },
            input,
        ))
    }
}

/// Append-only ownership of the trailer prefix and its admitted syntax state.
pub struct State<'d> {
    source: Owned<resident::Budget<'d>>,
    parser: Cursor,
}

/// Newly admitted input retained with its original owner through capacity growth.
#[must_use = "append the admitted bytes to transfer their framing proof"]
pub struct Plan<'input, 'd, P = ()> {
    state: State<'d>,
    bytes: &'input [u8],
    next: P,
}

#[must_use]
pub struct Append<'input, 'd>(Plan<'input, 'd>);

type Prepared<'input, 'd> = ControlFlow<
    (Plan<'input, 'd>, NonZero<usize>),
    (Plan<'input, 'd, Cursor>, Option<NonZero<usize>>),
>;

#[derive(Debug)]
pub enum StoreError {
    Prefix(NonZero<usize>),
    Capacity(consume::Error),
}

impl Pending<'_> {
    pub const fn consumed(&self) -> NonZero<usize> {
        self.consumed
    }

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

    pub const fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    pub const CAPACITY: usize = Framing::DEFAULT.trailer_bytes;

    /// Copies the exact borrowed prefix before transferring its parsing proof.
    pub fn try_store<'d>(
        self,
        mut target: Owned<resident::Budget<'d>>,
    ) -> Result<State<'d>, Rejected<(Self, Owned<resident::Budget<'d>>), StoreError>> {
        if let Err(error) = StoreError::copy(&mut target, self.bytes) {
            return Err(Rejected::new((self, target), error));
        }
        Ok(State {
            source: target,
            parser: self.cursor,
        })
    }
}

impl<'d> State<'d> {
    pub fn len(&self) -> usize {
        self.source.len()
    }

    pub fn is_empty(&self) -> bool {
        self.source.is_empty()
    }

    pub fn prepare<'input>(
        self,
        input: &'input [u8],
    ) -> Result<Prepared<'input, 'd>, Rejected<Self, Error>> {
        let (next, bytes) = match self.parser.scan(input, &Framing::DEFAULT) {
            Ok(next) => next,
            Err(error) => return Err(Rejected::new(self, error)),
        };
        Ok(match next {
            Progress::More { next, consumed } => ControlFlow::Continue((
                Plan {
                    state: self,
                    bytes,
                    next,
                },
                consumed,
            )),
            Progress::Complete { consumed, .. } => ControlFlow::Break((
                Plan {
                    state: self,
                    bytes,
                    next: (),
                },
                consumed,
            )),
        })
    }
}

impl<'d, P> Plan<'_, 'd, P> {
    pub fn len(&self) -> usize {
        self.state.len()
    }

    pub fn is_empty(&self) -> bool {
        self.state.is_empty()
    }

    pub fn cancel(self) -> State<'d> {
        self.state
    }

    /// Copies only the retained prefix; the new input's admission remains intact.
    pub fn try_grow(
        &mut self,
        mut target: Owned<resident::Budget<'d>>,
    ) -> Result<(), Rejected<Owned<resident::Budget<'d>>, StoreError>> {
        if let Err(error) = StoreError::copy(&mut target, self.state.source.as_ref()) {
            return Err(Rejected::new(target, error));
        }
        self.state.source = target;
        Ok(())
    }
}

impl<'d> Plan<'_, 'd, Cursor> {
    pub fn try_append(&mut self) -> Result<(), consume::Error> {
        let mut spare = self.state.source.spare();
        spare.write_slice(self.bytes)?;
        o3::buffer::write::Commit::commit(spare);
        self.state.parser = self.next;
        self.bytes = &[];
        Ok(())
    }
}

impl<'input, 'd> Plan<'input, 'd> {
    pub fn try_append(self) -> Result<Append<'input, 'd>, Rejected<Self, consume::Error>> {
        let source = &self.state.source;
        match consume::Error::check(self.bytes.len(), source.capacity() - source.len()) {
            Ok(()) => Ok(Append(self)),
            Err(error) => Err(Rejected::new(self, error)),
        }
    }
}

impl<'input, 'd> Append<'input, 'd> {
    pub fn cancel(self) -> Plan<'input, 'd> {
        self.0
    }

    pub fn commit(self) -> Owned<resident::Budget<'d>> {
        let plan = self.0;
        let mut source = plan.state.source;
        let start = source.len();
        let bytes = plan.bytes;
        // SAFETY: admission retained this exclusive owner with room for all bytes.
        // The completed scan admitted the final CRLF across both slices.
        unsafe {
            if bytes.len() > 2 {
                bytes
                    .as_ptr()
                    .copy_to_nonoverlapping(source.as_mut_ptr().add(start), bytes.len() - 2);
            }
            o3::buffer::raw::Target::set_len(&mut source, start + bytes.len() - 2);
        }
        source
    }
}

impl StoreError {
    fn copy(target: &mut Owned<resident::Budget<'_>>, bytes: &[u8]) -> Result<(), Self> {
        if let Some(len) = NonZero::new(target.len()) {
            return Err(Self::Prefix(len));
        }
        target.write_slice(bytes).map_err(Self::Capacity)
    }
}

/// Admitted field lines, excluding the section's terminating empty line.
/// Each retained line has a permitted name, colon, value, and CRLF.
pub struct Fields<'a> {
    lines: &'a [u8],
}

impl<'a> Fields<'a> {
    pub(in crate::h1) fn new(lines: &'a [u8]) -> Self {
        Self { lines }
    }

    /// Returns the remaining field section without the terminating empty line.
    pub const fn section(&self) -> &'a [u8] {
        self.lines
    }
}

impl<'a> Iterator for Fields<'a> {
    type Item = (&'a [u8], &'a [u8]);

    fn next(&mut self) -> Option<Self::Item> {
        let (name, value, rest) = Entry::split(self.lines)?;
        self.lines = rest;
        Some((name, field::Error::trim_ows(value)))
    }
}

const _: () = assert!(mem::size_of::<Fields<'_>>() == 2 * mem::size_of::<usize>());