dope-core 0.75.0

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

use dope_sys::thread;

use crate::platform::thread::{Error, Finished, Slot, Task, Value};

pub(super) struct Group<T, O, P> {
    pub(super) slots: Vec<Slot<T, O, P>>,
    /// Successful spawn prefix; this owner retains every remaining input.
    pub(super) started: usize,
}

impl<T, O, P> Drop for Group<T, O, P> {
    fn drop(&mut self) {
        self.take();
    }
}

impl<T, O, P> Group<T, O, P> {
    pub(super) fn parents_mut(&mut self) -> impl ExactSizeIterator<Item = &mut P> {
        let slots = self.slots.as_mut_ptr();
        (0..self.started).map(move |index| {
            // SAFETY: the started prefix lies within this fixed allocation.
            // Native entries access only task/output cells; this projection
            // lends only disjoint coordinator metadata for the Group borrow.
            unsafe {
                let slot = slots.add(index);
                &mut *ptr::addr_of_mut!((*slot).parent)
            }
        })
    }

    /// Joins every worker, drops unstarted inputs, and transfers the output prefix.
    pub(super) fn take(&mut self) -> Finished<T, O, P> {
        // SAFETY: successful spawns alone extend started within this fixed
        // allocation; Workers cannot grow or remove slots before this take.
        for slot in unsafe { self.slots.get_unchecked(..self.started) } {
            // SAFETY: start stores each handle before extending this prefix.
            // This take consumes each handle and then clears the prefix before
            // any later drop; Handle retains thread confinement.
            let handle = unsafe {
                slot.thread
                    .replace(mem::MaybeUninit::uninit())
                    .assume_init()
            };
            handle.join();
        }
        let len = self.slots.len();
        let slots = self.slots.as_mut_ptr();
        // SAFETY: started fits this fixed allocation. The detached suffix
        // stays initialized and exclusively owned here until consumed below.
        unsafe { self.slots.set_len(self.started) };
        for index in self.started..len {
            // SAFETY: each suffix task and parent remains initialized here.
            // Consume both in original order without moving their storage.
            unsafe {
                let slot = slots.add(index);
                mem::ManuallyDrop::drop(&mut (*slot).value.get_mut().task);
                ptr::drop_in_place(ptr::addr_of_mut!((*slot).parent));
            }
        }
        self.started = 0;
        Finished {
            slots: mem::take(&mut self.slots).into_iter(),
        }
    }
}

// SAFETY: the enclosing native owner retains this exact transfer cell until
// its handle joins; task and output are accessed only by that native entry.
unsafe impl<T: Task<Output = O>, O> thread::raw::Task for Value<T, O> {
    unsafe fn run(context: ptr::NonNull<Self>) {
        // SAFETY: successful spawn transfers the initialized input once.
        let value = context.as_ptr();
        let task = unsafe { mem::ManuallyDrop::take(&mut (*value).task) };
        let output = task.run();
        // SAFETY: native join publishes this initialized output to its owner.
        unsafe { (*value).output = mem::ManuallyDrop::new(output) };
    }
}

/// A single started worker borrowed from its enclosing native owner.
pub struct Join<'scope, O> {
    worker: &'scope mut Option<Worker<O>>,
}

struct Worker<O> {
    thread: mem::ManuallyDrop<thread::Handle>,
    output: ptr::NonNull<O>,
}

/// Runs with one worker retained until native joining, even if Join is forgotten.
pub fn scope<T: Task, R>(
    task: T,
    stack: NonZero<usize>,
    run: impl for<'scope> FnOnce(Join<'scope, T::Output>) -> R,
) -> Result<R, Error> {
    let attrs = match thread::Attrs::with_stack(stack) {
        Ok(attrs) => attrs,
        Err(error) => {
            drop(run);
            drop(task);
            return Err(Error::Attributes(error));
        }
    };
    let value = cell::UnsafeCell::new(Value {
        task: mem::ManuallyDrop::new(task),
    });
    // SAFETY: value stays at this address until the enclosing Worker joins.
    // No reference to the live task/output field is exposed to the parent.
    let entry = unsafe {
        thread::raw::Entry::new(ptr::NonNull::new_unchecked(value.get()))
    };
    let handle = match entry.spawn(&attrs) {
        Ok(handle) => handle,
        Err(error) => {
            drop(attrs);
            drop(run);
            // SAFETY: rejected spawn did not transfer or run this input.
            unsafe { mem::ManuallyDrop::drop(&mut (*value.get()).task) };
            return Err(Error::Create(error));
        }
    };
    drop(attrs);
    // SAFETY: this is the exact union output field. The pointer is retained
    // without dereferencing it until the corresponding native handle joins.
    let output = unsafe {
        ptr::NonNull::new_unchecked(ptr::addr_of_mut!((*value.get()).output).cast())
    };
    let mut worker = Some(Worker {
        thread: mem::ManuallyDrop::new(handle),
        output,
    });
    Ok(run(Join { worker: &mut worker }))
}

impl<O> Join<'_, O> {
    pub fn finish(self) -> O {
        // SAFETY: scope constructs one Join immediately from Some(Worker).
        // No other access can consume it during this exclusive loan; finish
        // consumes the sole Join and clears its enclosing owner before effects.
        let worker = unsafe {
            let worker = self.worker.as_mut_slice().as_mut_ptr().read();
            ptr::write(self.worker, None);
            worker
        };
        worker.finish()
    }
}

impl<O> Worker<O> {
    fn finish(self) -> O {
        let mut this = mem::ManuallyDrop::new(self);
        // SAFETY: this owner consumes its handle once. Native join completes
        // before reading the one initialized output at the retained address.
        unsafe {
            mem::ManuallyDrop::drop(&mut this.thread);
            this.output.as_ptr().read()
        }
    }
}

impl<O> Drop for Worker<O> {
    fn drop(&mut self) {
        // SAFETY: only a still-owned Worker reaches this destructor. Join first;
        // then consume its unread output before the lexical value backing ends.
        unsafe {
            mem::ManuallyDrop::drop(&mut self.thread);
            ptr::drop_in_place(self.output.as_ptr());
        }
    }
}