use std::{cell, convert::Infallible, marker::PhantomData, mem, num, ops, ptr};
use crate::{
alloc,
depot::{
self, capacity,
queue::{
links,
resident::{Bounds, Capacity, Grant, Lane, Lanes, Reject, handoff},
round,
},
},
};
unsafe impl<T, L, E> alloc::raw::Shape for Capacity<T, L, E> {
type Root = depot::raw::Node<T>;
type Tail = depot::raw::Node<links::raw::Chain>;
type Extra = E;
type Last = ();
fn len(&self) -> usize {
self.count.get()
}
fn tail_len(&self) -> usize {
self.lanes.get() as usize
}
}
pub struct View<'a, T> {
item: &'a depot::raw::Node<T>,
key: links::Index,
}
impl<T> ops::Deref for View<'_, T> {
type Target = depot::raw::Node<T>;
fn deref(&self) -> &Self::Target {
self.item
}
}
impl<'a, T> View<'a, T> {
pub unsafe fn new(entries: &'a [depot::raw::Node<T>], key: links::Index) -> Self {
let item = unsafe { entries.get_unchecked(key.get()) };
Self { item, key }
}
pub unsafe fn reserve_back(
free: &links::Free,
entries: &'a [depot::raw::Node<T>],
) -> Option<Self> {
let view = unsafe { Self::new(entries, free.front()?) };
unsafe { free.acquire_hook(view.hook()) };
Some(view)
}
pub fn key(&self) -> &links::Index {
&self.key
}
pub fn into_ref(self) -> &'a depot::raw::Node<T> {
self.item
}
fn is_parked(&self) -> bool {
self.item.hook().next.get() == self.key.raw()
}
pub(super) unsafe fn detached(&self) -> links::Detached<'a> {
unsafe { links::Detached::new(self.item.hook(), self.key) }
}
}
const _: () = {
assert!(mem::size_of::<View<'static, u64>>() == 2 * mem::size_of::<usize>());
assert!(mem::size_of::<Option<View<'static, u64>>>() == 2 * mem::size_of::<usize>());
};
union Payload<W, G> {
value: mem::ManuallyDrop<W>,
grant: mem::ManuallyDrop<G>,
}
pub struct Entry<W, G = Infallible> {
payload: cell::Cell<mem::MaybeUninit<Payload<W, G>>>,
}
impl<W, G> Default for Entry<W, G> {
fn default() -> Self {
Self {
payload: cell::Cell::new(mem::MaybeUninit::uninit()),
}
}
}
impl<W, G> Entry<W, G> {
fn payload(&self) -> *mut Payload<W, G> {
self.payload.as_ptr().cast()
}
pub fn initialize(&self, value: W)
where
W: Copy,
{
unsafe { (&raw mut (*self.payload()).value).write(mem::ManuallyDrop::new(value)) };
}
pub unsafe fn take(&self) -> W {
unsafe { mem::ManuallyDrop::take(&mut (*self.payload()).value) }
}
pub(super) unsafe fn take_grant(&self) -> G {
unsafe { mem::ManuallyDrop::take(&mut (*self.payload()).grant) }
}
}
type Joined<'a, W, G> =
round::raw::Join<'a, [depot::raw::Node<Entry<W, G>>], [depot::raw::Node<links::raw::Chain>]>;
impl<'a> View<'a, links::raw::Chain> {
pub(super) fn try_index<W, L, G, P>(
owner: &Lanes<W, L, G, P>,
index: usize,
) -> Result<links::Index, Bounds<num::NonZero<u32>>> {
let lanes = owner.storage.extent().lanes;
if index >= lanes.get() as usize {
return Err(Bounds::new(index, lanes));
}
Ok(unsafe { links::Index::new_usize(index) })
}
pub fn lane<W>(
source: depot::raw::Proof<(&'a Lanes<W>, usize), capacity::Physical>,
) -> Lane<'a, Lanes<W>> {
let (owner, index) = source.into_inner();
Lane::new(owner, unsafe { links::Index::new_usize(index) })
}
pub(super) fn join<W, L, G, P>(lane: Lane<'a, Lanes<W, L, G, P>>) -> Joined<'a, W, G> {
let lanes = lane.owner.storage.tail();
let entries = unsafe { Self::new(lanes, lane.index) }.into_ref();
round::raw::Join {
hooks: lane.owner.storage.as_ref(),
lanes,
entries,
active: &lane.owner.round,
index: lane.index,
}
}
}
impl<W, G> Entry<W, G> {
unsafe fn detach<const ACTIVE: bool, const ROTATE: bool, const PARK: bool>(
lane: Joined<'_, W, G>,
index: links::Index,
) -> &Self {
let node = unsafe { View::new(lane.hooks, index) }.into_ref();
let vacant = unsafe { lane.detach::<true, ACTIVE, ROTATE>(index, node.hook()) };
if PARK {
vacant.park();
} else {
vacant.idle();
}
node
}
pub(super) fn take_active<const ROTATE: bool, L, P>(owner: &Lanes<W, L, G, P>) -> Option<W> {
let lane = View::join(Lane::new(owner, owner.round.first()?));
let index = unsafe { lane.entries.front_key() };
Some(unsafe { Self::detach::<true, ROTATE, false>(lane, index).take() })
}
fn pop<const PARK: bool, L, P>(lane: Lane<'_, Lanes<W, L, G, P>>) -> Option<&Self> {
let lane = View::join(lane);
let index = lane.entries.first()?;
Some(unsafe { Self::detach::<false, false, PARK>(lane, index) })
}
pub(super) fn take_front<L, P>(lane: Lane<'_, Lanes<W, L, G, P>>) -> Option<W> {
Some(unsafe { Self::pop::<false, _, _>(lane)?.take() })
}
pub(super) fn offer<L>(
lane: Lane<'_, Lanes<W, L, G, usize>>,
grant: G,
) -> handoff::Offer<W, G> {
let Some(entry) = Self::pop::<true, _, _>(lane) else {
return handoff::Offer::Empty(grant);
};
let value = unsafe { entry.take() };
unsafe { (&raw mut (*entry.payload()).grant).write(mem::ManuallyDrop::new(grant)) };
handoff::Offer::Value(value)
}
}
pub(super) struct Binding<'a, T> {
owner: &'a T,
index: links::Index,
lane: links::Index,
target: PhantomData<cell::Cell<&'a T>>,
}
impl<'a, W, L, G, P: Grant> Binding<'a, Lanes<W, L, G, P>> {
pub(super) fn lane(&self) -> Lane<'a, Lanes<W, L, G, P>> {
Lane::new(self.owner, self.lane)
}
fn view(&self) -> View<'a, Entry<W, G>> {
unsafe { View::new(self.owner.storage.as_ref(), self.index) }
}
unsafe fn unlink(&self, view: &View<'a, Entry<W, G>>) -> links::Detached<'a> {
unsafe {
View::join(self.lane()).detach::<false, false, false>(self.index, view.item.hook())
}
}
pub(super) fn keep(
active: &mut Option<Self>,
lane: Lane<'a, Lanes<W, L, G, P>>,
value: W,
) -> Result<(), Reject<P>>
where
W: Copy,
{
let index = lane.index.get();
let view = match active {
Some(binding) => {
let view = binding.view();
let same = ptr::eq(binding.owner, lane.owner);
let linked = same && binding.index.is_linked(view.hook());
if !linked
&& let Some(index) = P::from_lane(index)
&& view.is_parked()
{
return Err(Reject::GrantPending { index });
}
if !same {
return Err(Reject::Active { index });
}
if !linked || binding.lane != lane.index {
let vacant = if linked {
unsafe { binding.unlink(&view) }
} else {
unsafe { view.detached() }
};
unsafe { View::join(lane).push(vacant) };
binding.lane = lane.index;
}
view
}
None => {
let view =
unsafe { View::reserve_back(&lane.owner.free, lane.owner.storage.as_ref()) }
.ok_or(Reject::Full { index })?;
unsafe { View::join(lane).push(view.detached()) };
*active = Some(Self {
owner: lane.owner,
index: view.key,
lane: lane.index,
target: PhantomData,
});
view
}
};
view.initialize(value);
Ok(())
}
pub(super) fn remove(&self) -> handoff::Cancel<G> {
let view = self.view();
let (vacant, result) = if self.index.is_linked(view.hook()) {
let vacant = unsafe { self.unlink(&view) };
(vacant, handoff::Cancel::Wake)
} else {
let result = if P::from_lane(self.lane.get()).is_some() && view.is_parked() {
handoff::Cancel::Grant(unsafe { view.take_grant() })
} else {
handoff::Cancel::Empty
};
(unsafe { view.detached() }, result)
};
self.owner.free.recycle(vacant);
result
}
}
impl<W, L, G> Binding<'_, Lanes<W, L, G, usize>> {
pub(super) fn take_grant(active: &mut Option<Self>) -> handoff::Grant<G> {
let Some(binding) = active else {
return handoff::Grant::Empty;
};
let view = binding.view();
if !view.is_parked() {
return handoff::Grant::Pending;
}
let grant = unsafe { view.take_grant() };
binding.owner.free.recycle(unsafe { view.detached() });
*active = None;
handoff::Grant::Ready(grant)
}
}