use std::{cell, convert::Infallible, mem, ops};
use crate::depot::{self, queue::links};
pub use crate::depot::raw::Node;
pub struct View<'a, T> {
item: &'a Node<T>,
key: links::Index,
}
impl<T> Clone for View<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for View<'_, T> {}
impl<T> ops::Deref for View<'_, T> {
type Target = Node<T>;
fn deref(&self) -> &Self::Target {
self.item
}
}
impl<'a, T> View<'a, T> {
pub unsafe fn new(entries: &'a [Node<T>], key: links::Index) -> Self {
let item = unsafe { entries.get_unchecked(key.get()) };
Self { item, key }
}
pub unsafe fn acquire(free: &links::Free, entries: &'a [Node<T>]) -> Option<Self> {
let key = unsafe { depot::raw::Hooks::acquire(entries, free) }?;
Some(unsafe { Self::new(entries, key) })
}
pub fn key(&self) -> &links::Index {
&self.key
}
pub fn into_ref(self) -> &'a Node<T> {
self.item
}
pub(super) fn grant_index<P: super::GrantIndex>(self, lane: usize) -> Option<P> {
let index = P::from_lane(lane)?;
(self.item.hook().next.get() == self.key.raw()).then_some(index)
}
pub(super) unsafe fn detached(self) -> links::Detached<'a> {
unsafe { links::Detached::new(self.item.hook(), self.key) }
}
pub fn unpark(self) -> Option<links::Detached<'a>> {
self.item.hook().try_unpark(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 unsafe fn retire(&self) {
drop(unsafe { self.take() });
}
pub(super) fn write_grant(&self, grant: G) {
unsafe { (&raw mut (*self.payload()).grant).write(mem::ManuallyDrop::new(grant)) };
}
pub(super) unsafe fn take_grant(&self) -> G {
unsafe { mem::ManuallyDrop::take(&mut (*self.payload()).grant) }
}
}