sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::{mem::MaybeUninit, ptr, slice};

use o3::{
    alloc::tail,
    depot,
    depot::map::{compact, compact::Insert as _},
};

use crate::{
    field::metadata::{block, map::record::Span},
    payload::compress::dynamic::{
        ENTRY_OVERHEAD, Field, Whole, field, hash,
        index::{self, Key},
        mode,
        table::{
            self,
            delta::{
                self, Borrow,
                buffer::{self, Header, Storage},
            },
            state::Size,
        },
    },
};

/// Owns one stable table/journal pair for the entire transaction.
/// # Safety
/// Implementations must return the same pair, with no other access while owned.
pub unsafe trait Source {
    fn parts(&self) -> (&table::Table<mode::Direct>, &buffer::Storage);
    fn parts_mut(&mut self) -> (&mut table::Table<mode::Direct>, &mut buffer::Storage);

    /// # Safety
    /// The original finished journal must remain unchanged and may be applied only once.
    unsafe fn finished(&mut self) -> delta::Commit<Borrow<'_>> {
        let (table, pending) = self.parts_mut();
        delta::Commit {
            owner: Borrow::new(table, pending),
        }
    }
}

unsafe impl Source for Borrow<'_> {
    fn parts(&self) -> (&table::Table<mode::Direct>, &buffer::Storage) {
        (self.table, self.pending)
    }

    fn parts_mut(&mut self) -> (&mut table::Table<mode::Direct>, &mut buffer::Storage) {
        (self.table, self.pending)
    }
}

#[derive(Clone, Copy)]
#[repr(C)]
pub(super) struct Record {
    digest: hash::Digest,
    start: u32,
    name_end: u32,
    end: u32,
    validation: Whole,
}

const _: () = assert!(size_of::<Record>() == ENTRY_OVERHEAD);

fn indices(storage: &mut Storage) -> (&mut Header, &mut [MaybeUninit<u8>]) {
    let (head, tail) = storage.block.parts_mut();
    // SAFETY: construction binds this immutable, checked range to the same tail.
    let slots = unsafe { tail.get_unchecked_mut(head.indices.clone()) };
    (head, slots)
}

pub(super) fn initialize(storage: &mut Storage) {
    let (head, slots) = indices(storage);
    for (offset, slot) in slots.iter_mut().enumerate() {
        slot.write(head.index.byte(offset));
    }
}

pub(super) fn clear(storage: &mut Storage) {
    let (head, slots) = indices(storage);
    // SAFETY: initialize wrote the complete directory before the caller obtained Storage.
    unsafe { index::raw::reset(&head.index, slots.assume_init_mut()) };
    head.len = 0;
    head.used = 0;
}

fn directory(storage: &Storage) -> &[u8] {
    let tail = tail::raw::View::new(&storage.block);
    // SAFETY: this initialized range belongs to the layout of this exact block.
    unsafe {
        tail.as_slice()
            .get_unchecked(tail.header().indices.clone())
            .assume_init_ref()
    }
}

fn records(storage: &Storage) -> &[Record] {
    let tail = tail::raw::View::new(&storage.block);
    // SAFETY: len publishes complete aligned records after both directory insertions.
    unsafe { slice::from_raw_parts(tail.as_slice().as_ptr().cast(), tail.header().len as usize) }
}

fn field<'a>(storage: &'a Storage, record: &Record) -> Field<'a> {
    let tail = tail::raw::View::new(&storage.block);
    let head = tail.header();
    // SAFETY: all callers read a record from this block's published prefix. The
    // two ordered byte ranges were initialized before that record was published.
    let (name, value) = unsafe {
        let start = tail.as_slice().as_ptr().cast::<u8>().add(head.indices.end);
        (
            slice::from_raw_parts(
                start.add(record.start as usize),
                (record.name_end - record.start) as usize,
            ),
            slice::from_raw_parts(
                start.add(record.name_end as usize),
                (record.end - record.name_end) as usize,
            ),
        )
    };
    Field {
        name: Span::from_slice(name),
        value: Span::from_slice(value),
        proof: record.validation.name(),
        validation: record.validation,
    }
}

pub(super) fn get(storage: &Storage, ordinal: usize) -> Option<Field<'_>> {
    Some(field(storage, records(storage).get(ordinal)?))
}

pub(super) fn size(storage: &Storage, ordinal: usize) -> Option<Size> {
    let record = records(storage).get(ordinal)?;
    Some(Size::from_data(record.end - record.start))
}

pub(super) fn iter(
    storage: &Storage,
) -> impl DoubleEndedIterator<Item = (Field<'_>, hash::Digest, Size)> {
    records(storage).iter().map(|record| {
        (
            field(storage, record),
            record.digest,
            Size::from_data(record.end - record.start),
        )
    })
}

pub(super) fn append(
    storage: &mut Storage,
    entry: delta::Insertion<'_>,
) -> Result<(), delta::Failure> {
    let field = entry.probe.field();
    let name = field.name.len();
    let head = storage.header();
    let limit = field::NAME_LEN_MASK as usize;
    if name > limit {
        return Err(delta::Failure::Name {
            actual: name,
            limit,
        });
    }
    let ordinal = head.len;
    if ordinal >= head.entries {
        return Err(delta::Failure::Entries {
            len: ordinal as usize,
            limit: head.entries as usize,
        });
    }
    let start = head.used;
    let end =
        (start as usize)
            .checked_add(entry.size.data_len())
            .ok_or(delta::Failure::Length {
                name,
                value: field.value.len(),
            })?;
    if end > head.bytes as usize {
        return Err(delta::Failure::Bytes {
            required: end,
            limit: head.bytes as usize,
        });
    }
    let mut value = block::Value::new();
    value.extend(field.value);
    let record = Record {
        digest: entry.probe.digest(),
        start,
        name_end: start + name as u32,
        end: end as u32,
        validation: Whole::from_value(block::Name::classify(field.name), value),
    };
    let (head, bytes) = storage.block.parts_mut();
    let ptr = bytes.as_mut_ptr().cast::<u8>();
    // SAFETY: the admitted ordinal and both source lengths fit the disjoint record
    // and data planes of this exclusive journal. Neither source borrows the journal.
    unsafe {
        ptr.cast::<Record>().add(ordinal as usize).write(record);
        let out = ptr.add(head.indices.end + start as usize);
        ptr::copy_nonoverlapping(field.name.as_ptr(), out, name);
        ptr::copy_nonoverlapping(field.value.as_ptr(), out.add(name), field.value.len());
    }
    let storage = Insert::<0> { storage, ordinal }.insert();
    let storage = Insert::<1> { storage, ordinal }.insert();
    let head = storage.block.header_mut();
    head.len = ordinal + 1;
    head.used = record.end;
    Ok(())
}

pub(super) struct Lookup<'a> {
    pub(super) storage: &'a Storage,
    pub(super) key: Key,
}

unsafe impl compact::raw::Read for Lookup<'_> {
    fn layout(&self) -> compact::Layout {
        self.storage.header().index.layout(self.key)
    }

    fn bytes(&self) -> &[u8] {
        directory(self.storage)
    }
}

unsafe impl compact::raw::Source for Lookup<'_> {
    fn hash(value: compact::Value<'_, Self>) -> u64 {
        let owner = value.owner();
        // SAFETY: the occupied directory member is a published record in this journal.
        owner
            .key
            .of(unsafe { records(owner.storage).get_unchecked(value.index()) }.digest)
    }
}

unsafe impl<'a> compact::raw::Query for Lookup<'a> {
    type Item = (usize, Field<'a>);

    fn get(value: compact::Value<'_, Self>) -> Self::Item {
        let storage = value.owner().storage;
        let ordinal = value.index();
        // SAFETY: the member retains this journal and its initialized record.
        let record = unsafe { records(storage).get_unchecked(ordinal) };
        (storage.len() - ordinal - 1, field(storage, record))
    }
}

struct Insert<'a, const N: usize> {
    storage: &'a mut Storage,
    ordinal: u32,
}

unsafe impl<const N: usize> compact::raw::Read for Insert<'_, N> {
    fn layout(&self) -> compact::Layout {
        self.storage.header().index.layout(Key::staged::<N>())
    }

    fn bytes(&self) -> &[u8] {
        directory(self.storage)
    }
}

unsafe impl<const N: usize> compact::raw::Source for Insert<'_, N> {
    fn hash(value: compact::Value<'_, Self>) -> u64 {
        let tail = tail::raw::View::new(&value.owner().storage.block);
        // SAFETY: insertion initialized the new ordinal before touching either
        // directory. All earlier occupied members belong to the published prefix.
        let record = unsafe { &*tail.as_slice().as_ptr().cast::<Record>().add(value.index()) };
        Key::staged::<N>().of(record.digest)
    }
}

unsafe impl<const N: usize> compact::raw::Write for Insert<'_, N> {
    unsafe fn bytes_mut(&mut self) -> &mut [u8] {
        // SAFETY: initialize wrote the entire directory; insertion owns it exclusively.
        unsafe { indices(self.storage).1.assume_init_mut() }
    }
}

unsafe impl<'a, const N: usize> compact::raw::Insert for Insert<'a, N> {
    type Output = &'a mut Storage;

    fn input(&self) -> compact::Value<'_, Self> {
        // SAFETY: the admitted ordinal was initialized and has not entered this directory.
        compact::Value::new(unsafe { depot::raw::Proof::new((self, self.ordinal)) })
    }

    unsafe fn inserted(self) -> Self::Output {
        self.storage
    }
}