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;
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),
}
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(())
}
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);
}
}
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,
}
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
}
pub fn parents_mut(&mut self) -> impl ExactSizeIterator<Item = &mut P> {
raw::parents(self.group)
}
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)
}
}
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);
}
}
pub struct Join<'scope, O> {
worker: &'scope mut Option<(thread::raw::Handle, ptr::NonNull<O>)>,
}
impl<O> Join<'_, O> {
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)
}
}