dope-core 0.75.0

Owned native I/O and completion driver for dope
Documentation
use o3::mem::slot;

use crate::{driver::route, io};

use super::Member;

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

impl<'d> io::event::net::send::Owned<'d> {
    pub(crate) fn consume(
        owner: slot::Occupied<'_, Self>,
    ) -> crate::driver::retained::flight::storage::Complete<
        'd,
        crate::driver::retained::flight::Target,
        { crate::driver::retained::flight::INDEX_BITS },
        { crate::driver::retained::flight::GENERATION_BITS },
    > {
        let mut owner = owner.into_uninit();
        let pointer = owner.get_mut().as_mut_ptr();
        // SAFETY: the original final payload owns this initialized field. Its
        // remaining result and brand have no Drop; only completion moves out.
        let completion = unsafe { (&raw const (*pointer).completion).read() };
        std::mem::ManuallyDrop::into_inner(completion)
    }
}

impl Drop for io::event::net::send::Owned<'_> {
    fn drop(&mut self) {
        // SAFETY: this final owner retains the bound completion exactly once.
        // Finish may have detached the backing; finish handles that same state.
        unsafe { std::mem::ManuallyDrop::take(&mut self.completion) }.finish();
    }
}

impl<'event, 'd, T, S: route::Selection> Member<'event, 'd, T, S> {
    pub fn get(&self) -> &T {
        let payload =
            std::ptr::from_ref::<io::Event<'d>>(&self.dispatch.event).cast::<Payload<T>>();
        // SAFETY: private selection fixes T to this live repr(u8) variant;
        // the immutable Member borrow retains its destruction authority.
        unsafe { &(*payload).value }
    }

    pub fn into_occupied(self) -> slot::Occupied<'event, T> {
        let mut vacant = self.dispatch.event.into_uninit();
        let payload = vacant.get_mut().as_mut_ptr().cast::<Payload<T>>();
        // SAFETY: selection proves this complete repr(u8) payload. Consuming
        // Event's destruction authority transfers it to this initialized field.
        let value = unsafe { &raw mut (*payload).value };
        drop(vacant);
        unsafe { slot::Vacant::new(&mut *value.cast::<std::mem::MaybeUninit<T>>()).assume_init() }
    }

    pub fn take(self) -> (T, slot::Vacant<'event, io::Event<'d>>) {
        let mut vacant = self.dispatch.event.into_uninit();
        let payload = vacant.get_mut().as_mut_ptr().cast::<Payload<T>>();
        // SAFETY: selection proves this complete payload of the repr(u8) variant.
        // The fresh pointer is read once; the vacant owner cannot drop Event.
        let value = unsafe { (&raw const (*payload).value).read() };
        (value, vacant)
    }
}

impl<'event, 'd, S: route::Selection> Member<'event, 'd, io::event::net::recv::Data<'d>, S> {
    pub fn consume(
        self,
    ) -> (
        route::Erased<'d, route::kind::Recv, S>,
        io::event::batch::Flow,
        slot::Occupied<'event, io::recv::Lease<'d>>,
    ) {
        use io::event::{batch::Item, entry::Entry};

        let target = self.get().token().in_scope(self.dispatch.route);
        let flow = self.get().flow();
        let mut source = self.dispatch.event.into_uninit();
        type Data<'d> = Payload<Entry<'d, route::kind::Recv, Item<io::recv::Lease<'d>>>>;
        let pointer = source.get_mut().as_mut_ptr().cast::<Data<'d>>();
        // SAFETY: selection fixes this initialized RecvData field. Its copied
        // metadata has no Drop; only this Lease retains destruction authority.
        let value = unsafe { &raw mut (*pointer).value.value.value };
        drop(source);
        let lease = unsafe {
            slot::Vacant::new(&mut *value.cast::<std::mem::MaybeUninit<io::recv::Lease<'d>>>())
                .assume_init()
        };
        (target, flow, lease)
    }
}

impl<'event, 'd, S: route::Selection>
    Member<
        'event,
        'd,
        io::event::net::recv::Completion<'d, route::Route, crate::driver::receive::Exhausted<'d>>,
        S,
    >
{
    pub fn register(
        self,
        registration: crate::driver::receive::Registration<'d>,
    ) -> Result<
        std::task::Poll<crate::driver::receive::Attempt<'d>>,
        (Self, crate::driver::receive::Stale),
    > {
        use crate::driver::receive;
        use io::event::{batch::Item, entry::Entry};

        let super::Dispatch { event, route } = self.dispatch;
        let mut vacant = event.into_uninit();
        type Exhausted<'d> = Payload<Entry<'d, route::kind::Recv, Item<receive::Exhausted<'d>>>>;
        let payload = vacant.get_mut().as_mut_ptr().cast::<Exhausted<'d>>();
        // SAFETY: selection fixes this initialized field. Vacant has disarmed
        // Event's Drop, so the proof moves exactly once into Registration.
        let field = unsafe { &raw mut (*payload).value.value.value };
        let proof = unsafe { field.read() };
        match registration.exhausted(proof) {
            Ok(attempt) => Ok(attempt),
            Err((proof, cause)) => {
                // SAFETY: rejection returned the same affine proof. Restoring
                // that field makes the unchanged Event fully initialized again.
                unsafe { field.write(proof) };
                let event = unsafe { vacant.assume_init() };
                Err((Self::new(super::Dispatch { event, route }), cause))
            }
        }
    }
}

#[cfg(target_os = "linux")]
impl<'d> crate::ring::cqe::Envelope<'d> {
    pub(crate) fn received<'event>(
        &mut self,
        flight: crate::driver::retained::flight::Complete<'d>,
        proof: crate::driver::route::kind::Witness<crate::driver::route::kind::Recv>,
        len: io::transfer::Len,
        mut output: slot::Vacant<'event, io::Event<'d>>,
    ) -> Result<slot::Occupied<'event, io::Event<'d>>, crate::driver::result::poll::fault::Fault>
    {
        use crate::driver::{result::poll::fault::Violation, route::kind};
        use crate::io::event::{RECV_DATA, batch::Item, entry::Entry};
        use o3::buffer::storage::provided;

        let driver = flight.driver();
        let Some(buffer) = self.buffer.take() else {
            let cause = if driver.owners().is_full() {
                Violation::Provided(provided::fixed::Full {
                    capacity: driver.owners().capacity(),
                })
            } else {
                Violation::Buffer
            };
            return Err(self.reject_flight(flight, cause));
        };
        let flow = self.flow();
        let bid = (self.parts.flags.0 >> 16) as u16;
        type Received<'d> = Payload<Entry<'d, kind::Recv, Item<io::recv::Lease<'d>>>>;
        let raw = output.get_mut().as_mut_ptr().cast::<Received<'d>>();
        // SAFETY: Event is transparent over repr(u8) Kind; RecvData contains a
        // transparent Completion, repr(C) Entry and Item, and transparent Lease/Value.
        // This vacant final field is the exact Unique storage; no owner is live yet.
        let value = unsafe {
            (&raw mut (*raw).value.value.value)
                .cast::<std::mem::MaybeUninit<provided::Unique<'d, ()>>>()
        };
        let vacant = unsafe { slot::Vacant::new(&mut *value) };
        // SAFETY: Envelope retained this original BID and its sole selected entry.
        // The native bounded outcome also proves Lease's signed-byte extent.
        match unsafe { buffer.publish(bid, len.into_raw(), vacant) } {
            Ok(value) => drop(value.into_uninit()),
            Err((buffer, _)) => {
                self.buffer = Some(buffer);
                return Err(self.reject_flight(
                    flight,
                    Violation::BufferLength {
                        actual: len,
                        capacity: driver.layout().buffer_len(),
                    },
                ));
            }
        }
        let target = flight.bind(proof).settle(flow);
        // SAFETY: Unique is initialized and its destruction belongs to this final
        // Event. Install only the disjoint headers and the admitted RecvData tag.
        unsafe {
            (&raw mut (*raw).value.target).write(target);
            (&raw mut (*raw).value.value.flow).write(flow);
            (&raw mut (*raw).tag).write(RECV_DATA);
            Ok(output.assume_init())
        }
    }
}