sark-http 0.39.0

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

use dope_core::driver::schedule::clock;
use miniz_oxide::inflate::{TINFLStatus, core::DecompressorOxide};
use o3::buffer::{
    resident,
    storage::Owned,
    write::{self, SpareExt as _},
};

use crate::payload::{
    compress::inflate::{
        Checked, DecodeError, Error, Failure, Part, Plan,
        checked::STEP,
        input::{Chunk, Step},
    },
    crc32::Hasher,
};

#[derive(Default)]
pub struct Gzip(DecompressorOxide, Hasher);

const _: () = assert!(
    mem::size_of::<Gzip>() == mem::size_of::<DecompressorOxide>() + mem::size_of::<usize>()
);

impl Gzip {
    /// Admits the header with checkpoints during bounded scans and CRC updates.
    pub fn try_plan<'a, const N: usize, I: Iterator<Item = &'a [u8]>, E: Copy>(
        &self,
        segments: I,
        hint: usize,
        checks: &[clock::Check<'_, E>; N],
    ) -> Result<Plan<'a, I>, Checked<Failure, E>> {
        for check in checks {
            check.check().map_err(Checked::Check)?;
        }
        Plan::try_header::<N, E>(segments, hint, Some(&self.1), checks)
    }

    pub fn decode<'a, I>(&mut self, segments: I, output: write::Spare<'_>) -> Result<(), Failure>
    where
        I: Iterator<Item = &'a [u8]>,
    {
        let plan = self.try_plan::<0, _, Infallible>(segments, 0, &[]).map_err(Checked::into_work)?;
        self.decode_exact(plan, output)
    }

    pub fn decode_plan<'a, I: Iterator<Item = &'a [u8]>>(
        &mut self,
        plan: Plan<'a, I>,
        output: write::Spare<'_>,
    ) -> Result<(), Failure> {
        if output.len() < plan.size_hint {
            return Err(Failure::new(
                Error::Length {
                    expected: plan.size_hint,
                    actual: output.len(),
                },
                0,
            ));
        }
        self.decode_exact(plan, output)
    }

    fn decode_exact<'a, I>(
        &mut self,
        plan: Plan<'a, I>,
        mut output: write::Spare<'_>,
    ) -> Result<(), Failure>
    where
        I: Iterator<Item = &'a [u8]>,
    {
        let written = self
            .decode_input::<0, _, _, Failure, Infallible>(
                plan,
                &mut output.as_mut_slice(),
                |output, _| {
                    let capacity = output.len();
                    Err(Failure::new(
                        Error::Output {
                            capacity,
                            written: capacity,
                        },
                        capacity,
                    )
                    .into())
                },
                &[],
            )
            .map_err(Checked::into_work)?;
        if written != output.len() {
            return Err(Failure::new(
                Error::Length {
                    expected: output.len(),
                    actual: written,
                },
                written,
            ));
        }
        output.commit();
        Ok(())
    }

    fn decode_input<'a, 'clock, const N: usize, I, B, D, E: Copy>(
        &mut self,
        plan: Plan<'a, I>,
        output: &mut B,
        mut grow: impl FnMut(&mut B, &[clock::Check<'clock, E>; N]) -> Result<(), Checked<D, E>>,
        checks: &[clock::Check<'clock, E>; N],
    ) -> Result<usize, Checked<D, E>>
    where
        I: Iterator<Item = &'a [u8]>,
        B: AsMut<[u8]>,
        D: From<Failure>,
    {
        let mut segments = plan.segments;
        let mut input = plan.input;
        let mut written = 0;
        let mut start = 0;
        loop {
            self.0.init();
            let mut checksum = self.1.clone();
            let mut trailer = {
                let mut cursor = input;
                loop {
                    for check in checks {
                        check.check().map_err(Checked::Check)?;
                    }
                    let step =
                        Chunk::next::<N, E>(cursor, &mut segments, checks).map_err(|error| {
                            error.failed::<D>(written)
                        })?;
                    let chunk = match step {
                        Step::Chunk(chunk) => chunk,
                        Step::End(end) => {
                            return Err(Failure::new(end.error(Part::Deflate), written).into());
                        }
                    };
                    let bytes = output.as_mut();
                    // SAFETY: the two private callers retain a fixed slice (growth fails)
                    // or grow its owner. Admitted writes and completed members preserve
                    // start <= written <= bytes.len().
                    let member = unsafe { bytes.get_unchecked_mut(start..) };
                    let (next, status, read, wrote) =
                        chunk.inflate::<N>(&mut self.0, member, written - start);
                    cursor = next;
                    let end = written + wrote;
                    // SAFETY: inflate admits wrote <= bytes.len() - written for this owner.
                    checksum.update(unsafe { bytes.get_unchecked(written..end) });
                    written = end;

                    match status {
                        TINFLStatus::Done => break cursor,
                        TINFLStatus::NeedsMoreInput if read != 0 || wrote != 0 => {}
                        TINFLStatus::HasMoreOutput if read != 0 || wrote != 0 => {}
                        TINFLStatus::HasMoreOutput => {
                            grow(output, checks)?;
                        }
                        cause => {
                            let error = Error::Inflate {
                                offset: cursor.consumed,
                                output: written,
                                cause,
                            };
                            return Err(Failure::new(error, written).into());
                        }
                    }
                }
            };

            let crc = trailer
                .u32::<N, E>(&mut segments, Part::Trailer, checks)
                .map_err(|error| error.failed::<D>(written))?;
            let actual = checksum.finalize();
            if actual != crc {
                let error = Error::Checksum {
                    expected: crc,
                    actual,
                };
                return Err(Failure::new(error, written).into());
            }

            let expected = trailer
                .u32::<N, E>(&mut segments, Part::Trailer, checks)
                .map_err(|error| error.failed::<D>(written))?;
            let expected = expected as usize;
            let length = written - start;
            if length as u32 != expected as u32 {
                let error = Error::Length {
                    expected,
                    actual: length,
                };
                return Err(Failure::new(error, written).into());
            }

            let step = Chunk::next::<N, E>(trailer, &mut segments, checks)
                .map_err(|error| error.failed::<D>(written))?;
            match step {
                Step::End(_) => return Ok(written),
                Step::Chunk(chunk) => {
                    let first = chunk.first();
                    input = chunk.into_source();
                    if first != 0x1f {
                        let bytes = input
                            .remaining::<N, E>(&mut segments, checks)
                            .map_err(Checked::Check)?;
                        return Err(Failure::new(Error::Trailing { bytes }, written).into());
                    }
                    for check in checks {
                        check.check().map_err(Checked::Check)?;
                    }
                    input
                        .header::<N, E>(&mut segments, Some(&self.1), checks)
                        .map_err(|error| {
                            error.failed::<D>(written)
                        })?;
                }
            }
            start = written;
        }
    }

    /// Decodes into one owned allocation; checkpoints bound each work chunk to 64 KiB.
    pub fn decode_owned<'a, 'd, const N: usize, I: Iterator<Item = &'a [u8]>, E: Copy>(
        &mut self,
        plan: Plan<'a, I>,
        limit: usize,
        budget: &resident::Budget<'d>,
        checks: &[clock::Check<'_, E>; N],
    ) -> Result<Owned<resident::Budget<'d>>, Checked<DecodeError, E>> {
        let plan = plan.try_limit(limit).map_err(Checked::Work)?;
        for check in checks {
            check.check().map_err(Checked::Check)?;
        }
        let free = budget.available();
        let seed = plan.size_hint.min(STEP);
        let mut output = Owned::try_allocate(budget, seed).map_err(|cause| {
            Checked::Work(DecodeError::Allocation {
                requested: seed,
                available: free,
                cause,
            })
        })?;
        fill::<N, E>(&mut output, checks).map_err(Checked::Check)?;
        let written = self.decode_input::<N, _, _, DecodeError, E>(
            plan,
            &mut output,
            |output, checks| {
                let current = output.len();
                if current == limit {
                    return Err(Checked::Work(DecodeError::SizeLimit {
                        actual: current.saturating_add(1),
                        limit,
                    }));
                }
                if current == output.capacity() {
                    for check in checks {
                        check.check().map_err(Checked::Check)?;
                    }
                    let free = budget.available();
                    let target = current
                        .saturating_mul(2)
                        .min(current.saturating_add(free))
                        .max(current + 1)
                        .min(limit);
                    output.try_reserve(budget, target).map_err(|cause| {
                        Checked::Work(DecodeError::Allocation {
                            requested: target,
                            available: free,
                            cause,
                        })
                    })?;
                }
                fill::<N, E>(output, checks).map_err(Checked::Check)
            },
            checks,
        )?;
        output.truncate(written);
        for check in checks {
            check.check().map_err(Checked::Check)?;
        }
        Ok(output)
    }
}

fn fill<const N: usize, E: Copy>(
    output: &mut Owned<resident::Budget<'_>>,
    checks: &[clock::Check<'_, E>; N],
) -> Result<(), E> {
    static ZERO: [u8; STEP] = [0; STEP];
    let mut spare = output.spare();
    if N != 0 && spare.remaining() != 0 {
        for check in checks {
            check.check()?;
        }
    }
    spare.write(&ZERO);
    spare.commit();
    Ok(())
}