use std::{cell, marker, mem, pin::Pin, ptr::NonNull};
use o3::{base::marker::ThreadBound, depot};
use crate::{
driver::{
self,
route::table::conn,
schedule::{app, ready::wake},
},
executor::task::{
context,
wait::{Capacity, Error, Length, Registration, WakeStatus},
},
};
type Entry<'d> = depot::raw::Entry<cell::Cell<Option<Active<'d>>>>;
#[derive(Clone, Copy)]
struct Active<'d> {
target: NonNull<()>,
wake: wake::Waker<'d>,
}
struct Vacant<'a, 'target, 'd>(Pin<&'a Waiter<'target, 'd>>);
trait Endpoint<'d>: Sized {
fn admit(&self, wake: wake::Waker<'d>) -> Result<(), Error<'d>>;
fn attach<'target>(&'target self, vacant: Vacant<'_, 'target, 'd>);
fn detach(&self, entry: Pin<&Entry<'d>>);
fn take(&self, entry: Pin<&Entry<'d>>) -> Option<wake::Waker<'d>> {
let active = entry.value().take();
self.detach(entry);
active.map(|active| active.wake)
}
fn deliver(&self, entry: Pin<&Entry<'d>>, work: app::Work<'_, 'd>) -> WakeStatus {
let Some(lease) = work.lease() else {
return WakeStatus::Pending;
};
if let Some(wake) = self.take(entry) {
let _permit = lease.commit();
wake.wake();
}
WakeStatus::Complete
}
}
#[repr(align(2))]
pub struct Queue<'d> {
links: depot::raw::Links<cell::Cell<Option<Active<'d>>>>,
len: cell::Cell<usize>,
capacity: Capacity,
}
impl<'d> Queue<'d> {
pub const fn new(_: driver::Reference<'d>, capacity: Capacity) -> Self {
Self {
links: depot::raw::Links::new(),
len: cell::Cell::new(0),
capacity,
}
}
pub const fn for_conns(driver: driver::Reference<'d>, capacity: conn::Capacity) -> Self {
Self::new(driver, Capacity::new(capacity.count().get() as usize))
}
pub fn try_register<'target>(
&'target self,
waiter: Pin<&Waiter<'target, 'd>>,
context: &context::Context<'_, 'd>,
) -> Result<(), Error<'d>> {
let active = Active {
target: NonNull::from(self).cast(),
wake: context.completion(),
};
waiter.register(self, active)
}
pub fn wake(&self, work: app::Work<'_, 'd>) -> WakeStatus {
while let Some(entry) = self.links.front() {
if self.deliver(entry, work) == WakeStatus::Pending {
return WakeStatus::Pending;
}
}
WakeStatus::Complete
}
pub fn wake_all(&self) {
while let Some(entry) = self.links.front() {
if let Some(wake) = self.take(entry) {
wake.wake();
}
}
}
pub fn wake_one(&self, work: app::Work<'_, 'd>) -> WakeStatus {
match self.links.front() {
Some(entry) => self.deliver(entry, work),
None => WakeStatus::Complete,
}
}
pub fn len(&self) -> Length {
Length::new(self.len.get())
}
pub(in crate::executor::task::wait) fn contains(&self, waiter: &Waiter<'_, 'd>) -> bool {
waiter
.entry
.value()
.get()
.is_some_and(|active| active.target == NonNull::from(self).cast())
}
}
impl<'d> Endpoint<'d> for Queue<'d> {
fn admit(&self, wake: wake::Waker<'d>) -> Result<(), Error<'d>> {
if self.len.get() < self.capacity.get() {
Ok(())
} else {
Err(Error::QueueFull {
capacity: self.capacity,
wake,
})
}
}
fn attach<'target>(&'target self, vacant: Vacant<'_, 'target, 'd>) {
unsafe { self.links.push_back(vacant.0.project_ref().entry) };
self.len.set(self.len.get() + 1);
}
fn detach(&self, entry: Pin<&Entry<'d>>) {
unsafe { self.links.remove(entry) };
self.len.set(self.len.get() - 1);
}
}
#[repr(align(2))]
pub struct Slot<'d> {
waiter: cell::Cell<Option<NonNull<Entry<'d>>>>,
thread: marker::PhantomData<ThreadBound>,
}
impl<'d> Slot<'d> {
pub const fn new() -> Self {
Self {
waiter: cell::Cell::new(None),
thread: marker::PhantomData,
}
}
pub fn try_register<'target>(
&'target self,
waiter: Pin<&Waiter<'target, 'd>>,
context: &context::Context<'_, 'd>,
) -> Result<(), Error<'d>> {
let active = Active {
target: NonNull::from(self).cast::<()>().map_addr(|addr| addr | 1),
wake: context.completion(),
};
waiter.register(self, active)
}
pub fn wake_one(&self, work: app::Work<'_, 'd>) -> WakeStatus {
match self.entry() {
Some(entry) => self.deliver(entry, work),
None => WakeStatus::Complete,
}
}
pub fn wake(&self) {
if let Some(entry) = self.entry()
&& let Some(wake) = self.take(entry)
{
wake.wake();
}
}
fn entry(&self) -> Option<Pin<&Entry<'d>>> {
let ptr = self.waiter.get()?;
Some(unsafe { Pin::new_unchecked(ptr.as_ref()) })
}
}
impl<'d> Endpoint<'d> for Slot<'d> {
fn admit(&self, wake: wake::Waker<'d>) -> Result<(), Error<'d>> {
if self.waiter.get().is_some() {
Err(Error::SlotFull(wake))
} else {
Ok(())
}
}
fn attach<'target>(&'target self, vacant: Vacant<'_, 'target, 'd>) {
self.waiter
.set(Some(NonNull::from(vacant.0.project_ref().entry.get_ref())));
}
fn detach(&self, _: Pin<&Entry<'d>>) {
self.waiter.set(None);
}
}
impl Default for Slot<'_> {
fn default() -> Self {
Self::new()
}
}
#[pin_project::pin_project(PinnedDrop)]
#[repr(C)]
pub struct Waiter<'target, 'd> {
#[pin]
entry: Entry<'d>,
thread: ThreadBound,
target: marker::PhantomData<cell::Cell<&'target ()>>,
}
impl Default for Waiter<'_, '_> {
fn default() -> Self {
Self::new()
}
}
impl<'target, 'd> Waiter<'target, 'd> {
pub const fn new() -> Self {
Self {
entry: depot::raw::Entry::new(cell::Cell::new(None)),
thread: ThreadBound::NEW,
target: marker::PhantomData,
}
}
fn register<E: Endpoint<'d>>(
self: Pin<&Self>,
endpoint: &'target E,
next: Active<'d>,
) -> Result<(), Error<'d>> {
let active = self.entry.value();
let previous = active.get();
if let Some(old) = previous
&& old.target == next.target
{
if old.wake != next.wake {
active.set(Some(next));
old.wake.wake();
}
return Ok(());
}
endpoint.admit(next.wake)?;
if let Some(old) = previous {
self.unlink(old);
}
active.set(Some(next));
endpoint.attach(Vacant(self));
if let Some(old) = previous {
old.wake.wake();
}
Ok(())
}
fn unlink(self: Pin<&Self>, active: Active<'d>) {
if active.target.addr().get() & 1 == 0 {
let queue = unsafe { active.target.cast::<Queue<'d>>().as_ref() };
queue.detach(self.project_ref().entry);
} else {
let ptr = active.target.as_ptr().cast::<u8>().wrapping_sub(1);
let slot = unsafe { &*ptr.cast::<Slot<'d>>() };
slot.waiter.set(None);
}
}
pub fn unregister(self: Pin<&Self>) {
let state = self.entry.value();
if let Some(active) = state.get() {
state.set(None);
self.unlink(active);
}
}
pub fn registration(&self) -> Registration {
if self.entry.value().get().is_some() {
Registration::Active
} else {
Registration::Vacant
}
}
}
#[pin_project::pinned_drop]
impl PinnedDrop for Waiter<'_, '_> {
fn drop(self: Pin<&mut Self>) {
self.as_ref().unregister();
}
}
const _: () = {
assert!(mem::align_of::<Queue<'static>>() >= 2);
assert!(mem::align_of::<Slot<'static>>() >= 2);
assert!(mem::size_of::<Option<Active<'static>>>() == 3 * mem::size_of::<usize>());
assert!(
mem::size_of::<Option<wake::Waker<'static>>>() == mem::size_of::<wake::Waker<'static>>()
);
assert!(mem::size_of::<Queue<'static>>() == 4 * mem::size_of::<usize>());
assert!(mem::size_of::<Slot<'static>>() == mem::size_of::<usize>());
assert!(mem::size_of::<Waiter<'static, 'static>>() == 5 * mem::size_of::<usize>());
};