use core::{convert, pin, task::Poll};
use o3::depot::array;
use crate::{
driver::schedule::{
app,
ready::task::{self, Index, pool},
},
executor::task::context,
executor::task::{Fiber, Ready},
executor::task::{
batch::{Completed, Error, Pool, RootError, Running, Vacant, state},
storage::slots,
},
};
#[pin_project::pin_project(PinnedDrop)]
#[must_use = "a fiber does nothing unless it is driven"]
pub struct Join<'pool, 'd, F, const N: usize>
where
F: Fiber<'d>,
{
#[pin]
entries: [slots::raw::Entry<F, F::Output>; N],
bindings: task::raw::Bindings<'d, &'pool task::raw::Scheduler<'d, N>, N>,
state: state::State<N>,
root: Option<pool::Root<'d>>,
}
impl<'pool, 'd, F, const N: usize> Join<'pool, 'd, F, N>
where
F: Fiber<'d>,
{
pub fn new(pool: &'pool mut Pool<'d, N>) -> Self {
Self::from_table(
pool,
[const { slots::raw::Entry::vacant() }; N],
array::Len::ZERO,
)
}
pub fn from_array(pool: &'pool mut Pool<'d, N>, fibers: [F; N]) -> Self {
Self::from_map(pool, fibers, convert::identity)
}
pub fn from_map<P>(
pool: &'pool mut Pool<'d, N>,
input: [P; N],
mut make: impl FnMut(P) -> F,
) -> Self {
Self::from_table(
pool,
input.map(|value| slots::raw::Entry::new(make(value))),
array::Len::MAX,
)
}
pub fn from_fn(pool: &'pool mut Pool<'d, N>, mut make: impl FnMut(Index<N>) -> F) -> Self {
Self::from_table(
pool,
task::raw::map(|index| slots::raw::Entry::new(make(index))),
array::Len::MAX,
)
}
fn from_table(
pool: &'pool mut Pool<'d, N>,
entries: [slots::raw::Entry<F, F::Output>; N],
len: array::Len<N>,
) -> Self {
Self {
entries,
bindings: pool.0.borrow_slots(),
state: state::State::new(len),
root: None,
}
}
pub fn try_push(&mut self, fiber: F) -> Result<(), F> {
let Some(state) = self.state.vacancy() else {
return Err(fiber);
};
let entry = state.slot().get_mut(&mut self.entries);
slots::raw::insert(Vacant(entry), fiber);
state.commit();
Ok(())
}
fn fail(
mut self: pin::Pin<&mut Self>,
error: Error,
) -> Poll<Result<array::IntoIter<F::Output, N>, Error>> {
if self.as_mut().project().root.take().is_some() {
self.cancel();
}
Poll::Ready(Err(error))
}
fn cancel(self: pin::Pin<&mut Self>) {
let this = self.project();
let end = this.state.next();
let (_, bindings) = this.bindings.split();
for (slot, claim) in slots::raw::prefix(this.entries, end).zip(bindings.drain(end)) {
if claim.is_some() {
slots::raw::live(Running(slot)).discard();
}
}
}
}
fn poll_slot<'d, F: Fiber<'d>>(
slot: Running<'_, F, F::Output>,
context: &mut context::Context<'_, 'd>,
binding: impl task::raw::Binding<'d>,
) -> state::Completion {
let mut live = slots::raw::live(slot);
match slots::poll(live.fiber(), context, binding) {
Poll::Pending => state::Completion::Pending,
Poll::Ready((output, _reclaim)) => {
live.complete(output);
state::Completion::Ready
}
}
}
impl<'pool, 'd, F, const N: usize> Fiber<'d> for Join<'pool, 'd, F, N>
where
F: Fiber<'d>,
{
type Output = Result<array::IntoIter<F::Output, N>, Error>;
fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
let (mut owner, context) = call.into_parts();
let done = 'complete: {
let mut this = owner.as_mut().project();
if let Some(done) = this.state.completed() {
break 'complete Ok(done);
}
let (sched, mut bindings) = this.bindings.split();
let root = match pool::Root::try_new(context.waker().0) {
Ok(root) => root,
Err(error) => break 'complete Err(Error::Root(RootError::Invalid(error))),
};
match *this.root {
None => *this.root = Some(root),
Some(active) if active == root => {}
Some(active) => {
break 'complete Err(Error::Root(RootError::Changed {
active: active.id(),
observed: root.id(),
}));
}
}
let mut initial = true;
while let Some(fresh) = this.state.fresh() {
let index = task::raw::from_vacant(fresh.slot());
if initial {
initial = false;
} else if matches!(context.try_continue(), context::Continue::Exhausted) {
return Poll::Pending;
}
let binding = match bindings.start(root, index) {
Ok(binding) => binding,
Err(error) => break 'complete Err(Error::Task(error)),
};
let complete = poll_slot(
Running(task::raw::project(index, this.entries.as_mut())),
context,
binding,
);
if let state::Status::Done(done) = fresh.commit(complete) {
break 'complete Ok(done);
}
}
let Some(mut drain) = sched.ready.drain() else {
return Poll::Pending;
};
loop {
let pending = match this.state.pending() {
state::PendingState::Live(pending) => pending,
state::PendingState::Done(done) => break 'complete Ok(done),
};
let wake = if initial {
let Some(index) = drain.pop() else {
break;
};
initial = false;
index
} else {
match drain.next(context.work()) {
app::Next::Item(index, _permit) => index,
app::Next::Empty => break,
app::Next::Exhausted(_) => {
drop(drain);
context.requeue();
return Poll::Pending;
}
}
};
let index = wake.local();
let Some(binding) = bindings.resume(wake) else {
continue;
};
let complete = poll_slot(
Running(task::raw::project(index, this.entries.as_mut())),
context,
binding,
);
if let state::Status::Done(done) = pending.commit(complete) {
break 'complete Ok(done);
}
}
if !sched.ready.is_empty() {
drop(drain);
context.requeue();
}
return Poll::Pending;
};
let done = match done {
Ok(done) => done,
Err(error) => return owner.fail(error),
};
let this = owner.project();
*this.root = None;
let output = slots::raw::outputs(Completed {
entries: this.entries,
len: done,
});
Poll::Ready(Ok(output))
}
}
#[pin_project::pinned_drop]
impl<'d, F, const N: usize> PinnedDrop for Join<'_, 'd, F, N>
where
F: Fiber<'d>,
{
fn drop(self: pin::Pin<&mut Self>) {
if self.root.is_some() {
self.cancel();
}
}
}
const _: () = {
use core::mem;
let word = mem::size_of::<usize>();
assert!(mem::size_of::<Vacant<'static, (), ()>>() == word);
assert!(mem::size_of::<Option<Vacant<'static, (), ()>>>() == word);
assert!(mem::size_of::<Join<'static, 'static, Ready<()>, 0>>() == 4 * word);
assert!(mem::align_of::<Join<'static, 'static, Ready<()>, 0>>() == word);
assert!(mem::size_of::<Option<Join<'static, 'static, Ready<()>, 0>>>() == 4 * word);
};