o3 0.59.0

shared-nothing primitives
Documentation
use std::{mem, ptr};

use crate::depot::{
    arena::linked::{fifo, slots},
    raw::{self, Exact as _},
};

/// Capacity held for one unchanged, owned input operation.
pub(crate) struct Input<'a, T, S: raw::Input<T>> {
    store: &'a slots::Store<T>,
    source: S,
}

impl<'a, T, S: raw::Input<T>> Input<'a, T, S> {
    pub(crate) fn try_new(store: &'a slots::Store<T>, source: S) -> Result<Self, S::Error> {
        let count = source.count();
        if let Err(error) = store.check(count) {
            return Err(source.reject(error));
        }
        store.debit(count);
        Ok(Self { store, source })
    }

    fn into_parts(self) -> (&'a slots::Store<T>, S) {
        let input = mem::ManuallyDrop::new(self);
        // SAFETY: startup transfers the sole source and its reservation together.
        (input.store, unsafe { ptr::read(&input.source) })
    }

    /// # Safety
    /// The queue owns its unchanged disjoint partition in this input's store.
    pub(in crate::depot) unsafe fn append(self, queue: &mut fifo::Fifo) -> S::Output
    where
        S: raw::Start<T, Item = T, Context = ()>,
    {
        let (store, source) = self.into_parts();
        let (mut items, ()) = source.start();
        for value in &mut items {
            // SAFETY: each exact item consumes one debit in the queue's store.
            unsafe { slots::Live::claim(store, value).append_to(queue) };
        }
        // SAFETY: iteration reached its terminal None.
        unsafe { items.finish() }
    }

    /// # Safety
    /// The links belong to this input's store. On failure they retain every successful item.
    pub(crate) unsafe fn try_append<E>(
        self,
        links: &mut fifo::ends::Exclusive<slots::Index>,
    ) -> Result<S::Output, E>
    where
        S: raw::Start<T, Item = Result<T, E>, Context = ()>,
    {
        let (store, source) = self.into_parts();
        let (mut items, ()) = source.start();
        while let Some(item) = items.next() {
            let value = match item {
                Ok(value) => value,
                Err(error) => {
                    // The failed item and unread suffix fit the original debit.
                    store.refund(items.remaining().raw().wrapping_add(1));
                    return Err(error);
                }
            };
            unsafe { slots::Live::claim(store, value).append(links) };
        }
        // SAFETY: every item was linked and iteration returned None.
        Ok(unsafe { items.finish() })
    }
}

impl<T, S: raw::Input<T>> Drop for Input<'_, T, S> {
    fn drop(&mut self) {
        self.store.refund(self.source.count().raw());
    }
}