use std::{marker, mem};
use crate::depot::{
self,
arena::linked::{self, fifo, fifo::ends},
};
#[repr(transparent)]
#[derive(Debug)]
pub struct Index<Tag = ()> {
raw: u32,
domain: marker::PhantomData<fn(Tag) -> Tag>,
}
impl<Tag> Index<Tag> {
pub(crate) const NONE: Self = Self::new(u32::MAX);
pub(crate) const fn new(raw: u32) -> Self {
Self {
raw,
domain: marker::PhantomData,
}
}
pub(crate) const fn get(self) -> Option<u32> {
if self.raw == u32::MAX {
None
} else {
Some(self.raw)
}
}
pub(crate) const fn raw(self) -> u32 {
self.raw
}
}
impl<Tag> Clone for Index<Tag> {
fn clone(&self) -> Self {
*self
}
}
impl<Tag> Copy for Index<Tag> {}
impl<Tag> PartialEq for Index<Tag> {
fn eq(&self, other: &Self) -> bool {
self.raw == other.raw
}
}
impl<Tag> Eq for Index<Tag> {}
const _: () = {
assert!(mem::size_of::<Index>() == mem::size_of::<u32>());
assert!(mem::align_of::<Index>() == mem::align_of::<u32>());
};
impl<Tag> Index<Tag> {
pub(in crate::depot::arena::linked) unsafe fn link<T, const FRONT: bool>(
self,
queue: &mut fifo::Fifo<Tag>,
store: &linked::raw::Store<T>,
) {
if FRONT {
let [head, tail] = &mut queue.links.0;
unsafe { store.set_next(self, *head) };
if *head == Self::NONE {
*tail = self;
}
*head = self;
} else {
unsafe { queue.links.append_end(store, self) };
}
queue.len = queue.len.wrapping_add(1);
}
pub(in crate::depot) unsafe fn unlink<T>(
self,
queue: &mut fifo::Fifo<Tag>,
store: &linked::raw::Store<T>,
) {
unsafe { queue.links.unlink(store, self) };
queue.len = queue.len.wrapping_sub(1);
}
pub(in crate::depot) unsafe fn pop<T, const TRACK: bool>(
self,
queue: &mut fifo::Fifo<Tag>,
store: &linked::raw::Store<T>,
) -> T {
unsafe { self.unlink(queue, store) };
unsafe { store.take::<_, TRACK>(self) }
}
}
impl<Tag> ends::Exclusive<Index<Tag>> {
pub(crate) const unsafe fn from_ends(head: Index<Tag>, tail: Index<Tag>) -> Self {
Self([head, tail])
}
pub(crate) unsafe fn append_end<T>(
&mut self,
store: &linked::raw::Store<T>,
index: Index<Tag>,
) {
if let Some(previous) = self.back() {
unsafe { store.set_next(previous, index) };
} else {
self.0[0] = index;
}
self.0[1] = index;
}
pub(crate) unsafe fn append_chain<T>(&mut self, store: &linked::raw::Store<T>, source: Self) {
unsafe { store.set_next(self.tail_raw(), source.head_raw()) };
self.0[1] = source.tail_raw();
}
pub(crate) unsafe fn unlink<T>(&mut self, store: &linked::raw::Store<T>, index: Index<Tag>) {
unsafe { depot::raw::EndsPop::advance(self, store.next(index)) };
}
}
const _: () = assert!(mem::size_of::<ends::Exclusive<Index>>() == 2 * mem::size_of::<u32>());