dope-core 0.76.0

Owned native I/O and completion driver for dope
Documentation
use std::{cell, marker, mem, num::NonZero, ptr, vec};

use dope_sys::thread;
use o3::alloc::{self, VecExt};

use crate::Errno;

mod raw;
mod sealed;

/// A single owned input transferred into a worker and returned as an output.
pub trait Task: Send {
    type Output: Send;
    fn run(self) -> Self::Output;
}

impl<F: FnOnce() -> O + Send, O: Send> Task for F {
    type Output = O;

    fn run(self) -> O {
        self()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    Attributes(Errno),
    Create(Errno),
}

/// Builds the one allocation retained for the complete worker scope.
pub struct Builder<T, O, P> {
    slots: Vec<Slot<T, O, P>>,
}

impl<T, O, P> Builder<T, O, P> {
    pub fn try_new(capacity: usize) -> Result<Self, alloc::Error> {
        Ok(Self {
            slots: Vec::try_new(capacity)?,
        })
    }

    pub fn try_push(&mut self, task: T, parent: P) -> Result<(), alloc::Error> {
        alloc::VecExt::try_vacant(&mut self.slots)?.insert(Slot {
            value: cell::UnsafeCell::new(raw::Value::new(task)),
            thread: cell::Cell::new(mem::MaybeUninit::uninit()),
            parent,
        });
        Ok(())
    }

    /// Retains every started worker even if the borrowing view is forgotten.
    pub fn scope<R>(mut self, run: impl for<'scope> FnOnce(Workers<'scope, T, O, P>) -> R) -> R {
        let mut group = Group {
            slots: mem::take(&mut self.slots),
            started: 0,
        };
        let result = run(Workers {
            group: &mut group,
            owner: marker::PhantomData,
        });
        sealed::finish(&mut group);
        result
    }
}

impl<T, O, P> Drop for Builder<T, O, P> {
    fn drop(&mut self) {
        raw::cancel(self);
    }
}

/// A worker's parent-only metadata and private transfer storage.
pub struct Slot<T, O, P> {
    value: cell::UnsafeCell<raw::Value<T, O>>,
    thread: cell::Cell<mem::MaybeUninit<thread::raw::Handle>>,
    parent: P,
}

impl<T, O, P> Slot<T, O, P> {
    pub fn parent(&self) -> &P {
        &self.parent
    }
}

struct Group<T, O, P> {
    slots: Vec<Slot<T, O, P>>,
    started: usize,
}

/// Borrowing authority to start and observe the scope-owned workers.
pub struct Workers<'scope, T, O, P> {
    group: &'scope mut Group<T, O, P>,
    owner: marker::PhantomData<fn(&'scope ()) -> &'scope ()>,
}

impl<T, O, P> Workers<'_, T, O, P> {
    pub fn entries(&self) -> &[Slot<T, O, P>] {
        &self.group.slots
    }

    /// Mutably borrows only coordinator metadata for the started worker prefix.
    pub fn parents_mut(&mut self) -> impl ExactSizeIterator<Item = &mut P> {
        raw::parents(self.group)
    }

    /// Spawns the remaining workers or borrows the first failed worker's parent.
    pub fn start(&mut self, stack: NonZero<usize>) -> Result<(), (&P, Error)>
    where
        T: Task<Output = O>,
    {
        raw::start(self.group, stack)
    }

    pub fn finish(self) -> Finished<T, O, P> {
        sealed::finish(self.group)
    }
}

/// Joined outputs, in the original registration order.
pub struct Finished<T, O, P> {
    slots: vec::IntoIter<Slot<T, O, P>>,
}

impl<T, O, P> Iterator for Finished<T, O, P> {
    type Item = (P, O);

    fn next(&mut self) -> Option<Self::Item> {
        raw::next(self)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.slots.size_hint()
    }
}

impl<T, O, P> ExactSizeIterator for Finished<T, O, P> {}

impl<T, O, P> Drop for Finished<T, O, P> {
    fn drop(&mut self) {
        raw::discard_outputs(self);
    }
}

/// A single started worker borrowed from its enclosing native owner.
pub struct Join<'scope, O> {
    worker: &'scope mut Option<(thread::raw::Handle, ptr::NonNull<O>)>,
}

impl<O> Join<'_, O> {
    /// Runs with one worker retained until native joining, even if Join is forgotten.
    pub fn scope<T: Task<Output = O>, R>(
        task: T,
        stack: NonZero<usize>,
        run: impl for<'scope> FnOnce(Join<'scope, O>) -> R,
    ) -> Result<R, Error> {
        let attrs = thread::raw::Attrs::with_stack(stack).map_err(Error::Attributes)?;
        raw::single(task, attrs, run)
    }

    pub fn finish(self) -> O {
        raw::output(self)
    }
}