dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::{marker::PhantomData, mem::MaybeUninit};

use o3::{
    base::num::bounded,
    buffer::{
        bytes::bounded::MAX,
        storage::provided::{self, native, view::LengthError},
    },
    mem::slot,
};

use crate::{
    Errno,
    io::reactor::{
        complete::flags::Flow,
        event::{Entry, Item, Kind, Received, Retryable, kind},
    },
    memory::buffer::Access,
    table::{Slots, token::host::Flight},
};

#[repr(C)]
struct Payload<V> {
    tag: u8,
    value: V,
}

#[repr(transparent)]
pub struct Completion<'d, F: Flight>(Kind<'d, F>);

impl<'d, F: Flight> AsRef<Kind<'d, F>> for Completion<'d, F> {
    fn as_ref(&self) -> &Kind<'d, F> {
        &self.0
    }
}

impl<'d, F: Flight> From<Kind<'d, F>> for Completion<'d, F> {
    fn from(kind: Kind<'d, F>) -> Self {
        Self(kind)
    }
}

impl<'d, F: Flight> Completion<'d, F> {
    pub fn into_kind(self) -> Kind<'d, F> {
        self.0
    }

    pub fn accepted<D: Slots<F>>(
        flight: F,
        proof: kind::Witness<kind::Accept>,
        flow: Flow,
        result: Result<D::Accepted, F::AcceptFailure>,
        drain: &D,
    ) -> Self {
        let entry = Entry::new(flight, proof, flow);
        let value = match result {
            Ok(accepted) => drain.accepted(accepted),
            Err(error) => Err(error),
        };
        Self(Kind::Accept(entry.with_value(Item::new(flow, value))))
    }

    pub fn control<B, R: Access<B, F::Exhausted>>(
        flight: F,
        proof: kind::Witness<kind::Recv>,
        flow: Flow,
        outcome: Result<(), Errno>,
        driver: &R,
    ) -> Self {
        let entry = Entry::new(flight, proof, flow);
        Self(match outcome {
            Ok(()) => Kind::RecvEof(entry.with_value(Item::new(flow, ()))),
            Err(error) if error == Errno::NO_BUFFER_SPACE => {
                if flow == Flow::Last
                    && let Some(empty) = driver.try_exhaust()
                {
                    Kind::RecvExhausted(entry.with_value(Item::new(flow, empty)))
                } else {
                    Kind::RecvStarved(entry.with_value(Item::new(flow, Retryable(error))))
                }
            }
            Err(error) if error == Errno::CANCELED => {
                Kind::RecvCancelled(entry.with_value(Item::new(flow, ())))
            }
            Err(error) if error.is_intr() || error.is_block() => {
                Kind::RecvStarved(entry.with_value(Item::new(flow, Retryable(error))))
            }
            Err(error) => Kind::RecvFailed(entry.with_value(Item::new(flow, error))),
        })
    }
}
impl<'d, F: Flight> Completion<'d, F> {
    /// # Safety
    /// Retain the same driver flight, original selected BID and initialized native prefix.
    pub unsafe fn received<'event, C: native::raw::Context>(
        flight: F,
        proof: kind::Witness<kind::Recv>,
        flow: Flow,
        len: F::Length,
        buffer: native::raw::Pending<'d, C>,
        bid: u16,
        mut output: slot::raw::Vacant<'event, Self>,
    ) -> Result<slot::Occupied<'event, Self>, (F, native::raw::Pending<'d, C>, LengthError)> {
        type Output<'d, F> = Payload<Entry<F, kind::Recv, Item<Received<'d>>>>;
        let raw = output.get_mut().as_mut_ptr().cast::<Output<'d, F>>();
        // SAFETY: repr(u8)/C/transparent layouts put the final bounded Slice here.
        let value = unsafe { &raw mut (*raw).value.value.value };
        let value = value
            .cast::<MaybeUninit<provided::raw::Slice<&'d mut [u8], provided::raw::Owner<'d, ()>>>>(
            );
        let vacant = unsafe { slot::raw::Vacant::new(&mut *value) };
        let count: bounded::raw::U32<0, { MAX as u32 }> = len.into();
        // SAFETY: the caller retains this original BID; the bound fixes the signed extent.
        match unsafe { buffer.publish(bid, count.get() as usize, vacant) } {
            Ok(value) => drop(value.into_uninit()),
            Err((buffer, cause)) => return Err((flight, buffer, cause)),
        }
        let target = flight.settle(proof, flow);
        // SAFETY: publication owns the only initialized Slice. Headers are disjoint.
        unsafe {
            (&raw mut (*raw).value.target).write(target);
            (&raw mut (*raw).value.value.flow).write(flow);
            (&raw mut (*raw).value.flight).write(PhantomData);
            (&raw mut (*raw).tag).write(1);
            Ok(output.assume_init())
        }
    }
}