dope-core 0.77.0

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

use dope_sys::thread;

use crate::platform::thread::{Builder, Error, Finished, Group, Join, Slot, Task};

#[repr(C)]
pub(super) union Value<T, O> {
    task: mem::ManuallyDrop<T>,
    output: mem::ManuallyDrop<O>,
}

impl<T, O> Value<T, O> {
    pub(super) fn new(task: T) -> Self {
        Self {
            task: mem::ManuallyDrop::new(task),
        }
    }
}

// SAFETY: the enclosing native owner retains the cell and its loans until join.
unsafe impl<T: Task<Output = O>, O> thread::raw::Task for Value<T, O> {
    unsafe fn run(context: ptr::NonNull<Self>) {
        let value = context.as_ptr();
        // SAFETY: successful creation transfers the input once to this thread.
        let task = unsafe { mem::ManuallyDrop::take(&mut (*value).task) };
        let output = task.run();
        // SAFETY: the input is consumed; native join publishes the output.
        unsafe { (*value).output = mem::ManuallyDrop::new(output) };
    }
}

pub(super) fn cancel<T, O, P>(builder: &mut Builder<T, O, P>) {
    // SAFETY: only scope can start workers, after taking the complete allocation.
    unsafe { discard(&mut builder.slots, 0) };
}

unsafe fn discard<T, O, P>(slots: &mut Vec<Slot<T, O, P>>, started: usize) {
    let len = slots.len();
    let base = slots.as_mut_ptr();
    // SAFETY: the caller owns this initialized suffix. Detach it before running destructors.
    unsafe { slots.set_len(started) };
    for index in started..len {
        // SAFETY: each suffix slot owns both fields. Drop them in registration order in place.
        unsafe {
            let slot = &mut *base.add(index);
            mem::ManuallyDrop::drop(&mut slot.value.get_mut().task);
            ptr::drop_in_place(&raw mut slot.parent);
        }
    }
}

/// # Safety
/// The prefix must own one live handle per slot and the suffix its unstarted inputs.
/// Remove the prefix from the group's live state before using it again.
pub(super) unsafe fn reclaim<T, O, P>(group: &mut Group<T, O, P>) {
    // SAFETY: start stores each handle before extending the prefix. Native workers
    // access only their transfer cells, so only the handle is consumed during join.
    for slot in unsafe { group.slots.get_unchecked(..group.started) } {
        // SAFETY: reclaim consumes the live prefix once before publishing its outputs.
        drop(unsafe { (*slot.thread.as_ptr()).assume_init_read() });
    }
    // SAFETY: all live handles have joined, and each suffix slot still owns its input.
    unsafe { discard(&mut group.slots, group.started) };
}

pub(super) fn parents<T, O, P>(
    group: &mut Group<T, O, P>,
) -> impl ExactSizeIterator<Item = &mut P> {
    let slots = group.slots.as_mut_ptr();
    (0..group.started).map(move |index| {
        // SAFETY: distinct prefix indices point into fixed storage. Borrow only
        // the parent; the live native worker accesses the disjoint transfer cell.
        unsafe { &mut (*slots.add(index)).parent }
    })
}

pub(super) fn start<T: Task<Output = O>, O, P>(
    group: &mut Group<T, O, P>,
    stack: NonZero<usize>,
) -> Result<(), (&P, Error)> {
    // SAFETY: only successful spawns extend started within this fixed allocation.
    let pending = unsafe { group.slots.get_unchecked(group.started..) };
    let Some(first) = pending.first() else {
        return Ok(());
    };
    let attr = thread::raw::Attrs::with_stack(stack)
        .map_err(|error| (&first.parent, Error::Attributes(error)))?;
    for slot in pending {
        // SAFETY: this slot stays fixed and its task is exclusively transferred until
        // join. Publish the handle before counting the new worker or attempting another.
        let handle = unsafe { attr.spawn(ptr::NonNull::new_unchecked(slot.value.get())) }
            .map_err(|error| (&slot.parent, Error::Create(error)))?;
        slot.thread.set(mem::MaybeUninit::new(handle));
        group.started += 1;
    }
    Ok(())
}

pub(super) fn next<T, O, P>(finished: &mut Finished<T, O, P>) -> Option<(P, O)> {
    let Slot { value, parent, .. } = finished.slots.next()?;
    // SAFETY: this joined slot has one output, and next consumes it.
    Some((
        parent,
        mem::ManuallyDrop::into_inner(unsafe { value.into_inner().output }),
    ))
}

pub(super) fn discard_outputs<T, O, P>(finished: &mut Finished<T, O, P>) {
    for slot in finished.slots.as_mut_slice() {
        // SAFETY: each remaining joined slot owns an unread output.
        unsafe { mem::ManuallyDrop::drop(&mut slot.value.get_mut().output) };
    }
}

pub(super) fn single<T: Task<Output = O>, O, R>(
    task: T,
    attrs: thread::raw::Attrs,
    run: impl for<'scope> FnOnce(Join<'scope, O>) -> R,
) -> Result<R, Error> {
    let mut value = Value::<T, O>::new(task);
    let context = ptr::NonNull::from_mut(&mut value);
    // SAFETY: this stack slot stays fixed and untouched while the worker runs.
    let handle = match unsafe { attrs.spawn(context) } {
        Ok(handle) => handle,
        Err(error) => {
            drop(attrs);
            drop(run);
            // SAFETY: rejected creation leaves the input exclusively owned here.
            unsafe { mem::ManuallyDrop::drop(&mut value.task) };
            return Err(Error::Create(error));
        }
    };
    drop(attrs);
    // SAFETY: repr(C) places the output at the union address; only join permits reading it.
    let mut worker = Some((handle, context.cast()));
    let result = run(Join {
        worker: &mut worker,
    });
    if let Some((handle, output)) = worker {
        drop(handle);
        // SAFETY: an unfinished view leaves the single published output here.
        unsafe { output.drop_in_place() };
    }
    Ok(result)
}

pub(super) fn output<O>(join: Join<'_, O>) -> O {
    // SAFETY: scope creates one view of a present handle; this consuming call
    // has the only authority to clear it and return the initialized output.
    let (handle, output) = unsafe {
        let worker = join.worker.as_mut_slice().as_mut_ptr().read();
        ptr::write(join.worker, None);
        worker
    };
    drop(handle);
    // SAFETY: this handle joined the worker that initialized this output.
    unsafe { output.read() }
}