sark-http 0.39.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::{borrow::Borrow, num::NonZero};

use crate::{
    field::{head::MAX_HEADER_LINE_BYTES, scan},
    h1::{
        field::{Limit, Progress, syntax::Error},
        head::line::{Parts, Request},
    },
};

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Phase {
    Name,
    Value { raw: u32 },
    ValueLf { raw: u32 },
    EndLf,
}

#[derive(Clone, Copy)]
pub struct Cursor {
    pub(super) line: u32,
    pub(super) cursor: u32,
    pub(super) seen: u32,
    pub(super) limit: Limit,
    pub(super) phase: Phase,
}

impl Cursor {
    pub fn after<P: Borrow<Parts>>(request: &Request<'_, P>, count: usize) -> Result<Self, Error> {
        Self::seed(request.end(), 0, Limit::new(count, MAX_HEADER_LINE_BYTES))
    }

    pub const fn fields(count: usize) -> Self {
        Self::new(0, Limit::new(count, MAX_HEADER_LINE_BYTES))
    }

    pub const fn field_start(&self) -> usize {
        self.line as usize
    }

    pub const fn next(&self) -> usize {
        (self.cursor as usize).saturating_add(
            matches!(self.phase, Phase::ValueLf { .. } | Phase::EndLf) as usize,
        )
    }

    pub(super) fn seed(start: usize, seen: usize, limit: Limit) -> Result<Self, Error> {
        let start = Self::try_narrow(start)?;
        let seen = Self::try_narrow(seen)?;
        if seen > limit.count {
            return Err(Error::TooMany);
        }
        Ok(Self {
            seen,
            ..Self::new(start, limit)
        })
    }

    pub(in crate::h1) const fn new(start: u32, limit: Limit) -> Self {
        Self {
            line: start,
            cursor: start,
            seen: 0,
            limit,
            phase: Phase::Name,
        }
    }

    #[inline(always)]
    pub fn read(&mut self, bytes: &[u8]) -> Result<Progress, Error> {
        let base = (self.cursor as usize)
            .checked_add(usize::from(matches!(
                self.phase,
                Phase::ValueLf { .. } | Phase::EndLf
            )))
            .ok_or(Error::TooLarge)?;
        let Some(&byte) = bytes.first() else {
            return Ok(Progress::More);
        };
        match self.phase {
            Phase::Name if self.cursor == self.line && byte == b'\r' => {
                self.ending(bytes.get(1).copied())
            }
            Phase::Name => match scan::Bytes::new(bytes).name(0) {
                scan::Outcome::Found((colon, b':')) => {
                    let at = base.checked_add(colon).ok_or(Error::TooLarge)?;
                    if at == self.line as usize {
                        return Err(Error::Name { offset: at, actual: b':' });
                    }
                    let raw = Self::try_narrow(at.checked_add(1).ok_or(Error::TooLarge)?)?;
                    self.value(bytes, base, colon + 1, raw)
                }
                scan::Outcome::Found((offset, actual))
                | scan::Outcome::Invalid { offset, actual } => Err(Error::Name {
                    offset: base.checked_add(offset).ok_or(Error::TooLarge)?,
                    actual,
                }),
                scan::Outcome::Partial => self.partial(
                    base.checked_add(bytes.len()).ok_or(Error::TooLarge)?,
                    Phase::Name,
                ),
            },
            Phase::Value { raw } => self.value(bytes, base, 0, raw),
            Phase::ValueLf { raw } if byte == b'\n' => self.admit(raw, self.cursor),
            Phase::ValueLf { .. } => Err(Error::Value { offset: base, actual: byte }),
            Phase::EndLf => self.ending(Some(byte)),
        }
    }

    fn value(
        &mut self,
        bytes: &[u8],
        base: usize,
        pos: usize,
        raw: u32,
    ) -> Result<Progress, Error> {
        match scan::Bytes::new(bytes).value(pos) {
            scan::Outcome::Found(end) => self.admit(
                raw,
                Self::try_narrow(base.checked_add(end).ok_or(Error::TooLarge)?)?,
            ),
            scan::Outcome::Invalid { offset, actual } => Err(Error::Value {
                offset: base.checked_add(offset).ok_or(Error::TooLarge)?,
                actual,
            }),
            scan::Outcome::Partial if bytes.last() == Some(&b'\r') => self.partial(
                base.checked_add(bytes.len() - 1).ok_or(Error::TooLarge)?,
                Phase::ValueLf { raw },
            ),
            scan::Outcome::Partial => self.partial(
                base.checked_add(bytes.len()).ok_or(Error::TooLarge)?,
                Phase::Value { raw },
            ),
        }
    }

    fn ending(&mut self, byte: Option<u8>) -> Result<Progress, Error> {
        let lf = self.cursor.checked_add(1).ok_or(Error::TooLarge)?;
        match byte {
            Some(b'\n') => {
                let wire = NonZero::<u32>::MIN.checked_add(lf).ok_or(Error::TooLarge)?;
                Ok(Progress::End(End::new(self.cursor, wire)))
            }
            Some(actual) => Err(Error::Ending { offset: lf as usize, actual }),
            None => self.partial(self.cursor as usize, Phase::EndLf),
        }
    }

    fn admit(&mut self, raw: u32, end: u32) -> Result<Progress, Error> {
        let next = end.checked_add(2).ok_or(Error::TooLarge)?;
        if end - self.line > self.limit.line_bytes {
            return Err(Error::TooLong);
        }
        if self.seen == self.limit.count {
            return Err(Error::TooMany);
        }
        let line = Line { start: self.line, raw, end };
        self.line = next;
        self.cursor = next;
        self.seen += 1;
        self.phase = Phase::Name;
        Ok(Progress::Field(line))
    }

    fn partial(&mut self, cursor: usize, phase: Phase) -> Result<Progress, Error> {
        let cursor = Self::try_narrow(cursor)?;
        if cursor - self.line > self.limit.line_bytes {
            return Err(Error::TooLong);
        }
        self.cursor = cursor;
        self.phase = phase;
        Ok(Progress::More)
    }

    pub(super) fn try_narrow(value: usize) -> Result<u32, Error> {
        u32::try_from(value).map_err(|_| Error::TooLarge)
    }
}

const _: () = assert!(core::mem::size_of::<Cursor>() == 28);

pub struct Line {
    pub(super) start: u32,
    pub(super) raw: u32,
    pub(super) end: u32,
}

impl Line {
    pub const fn start(&self) -> usize {
        self.start as usize
    }

    pub const fn wire_end(&self) -> usize {
        self.end as usize + 2
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct End {
    fields: u32,
    wire: NonZero<u32>,
}

impl End {
    pub(super) const fn new(fields: u32, wire: NonZero<u32>) -> Self {
        Self { fields, wire }
    }

    pub const fn fields(self) -> u32 {
        self.fields
    }

    pub const fn wire_len(self) -> NonZero<u32> {
        self.wire
    }
}

const _: () = {
    assert!(core::mem::size_of::<End>() == 8);
    assert!(core::mem::size_of::<Option<End>>() == 8);
};