use std::mem;
pub use bounds::Bounds;
use crate::depot::{capacity, queue::indexed::fifo};
mod bounds;
pub type Fifo<T, P = (), const N: usize = 1> = fifo::Store<T, P, N, ()>;
pub type Slot<'a, T, P = (), const N: usize = 1> = fifo::NodeEntry<'a, T, P, N, ()>;
impl<T: Copy, P: Default, const N: usize> Fifo<T, P, N> {
pub fn try_new(capacity: usize) -> Result<Self, crate::alloc::Error> {
Self::try_with(capacity, P::default)
}
}
impl<T: Copy, P, const N: usize> Fifo<T, P, N> {
pub fn try_with(capacity: usize, seed: impl FnMut() -> P) -> Result<Self, crate::alloc::Error> {
Self::try_count(
capacity::Count::try_count(capacity, crate::alloc::Error::Overflow)?,
seed,
)
}
pub fn is_empty<const Q: usize>(&self) -> bool {
self.chain::<Q>().is_empty()
}
pub fn try_entry(&self, index: usize) -> Result<Slot<'_, T, P, N>, Bounds> {
self.get(index).ok_or(Bounds {
index,
capacity: self.capacity(),
})
}
pub fn next<const Q: usize>(&self) -> Option<(Slot<'_, T, P, N>, T)> {
let index = self.chain::<Q>().first()?;
let slot = unsafe { self.at(index.get()) };
let value = unsafe { slot.take_head::<Q>(index) };
Some((slot, value))
}
pub fn pop_front<const Q: usize>(&self) -> Option<(usize, &P, T)> {
let index = self.chain::<Q>().first()?;
let slot = unsafe { self.at(index.get()) };
Some((index.get(), slot.state(), unsafe {
slot.take_head::<Q>(index)
}))
}
}
impl<T: Copy, P, const N: usize> Slot<'_, T, P, N> {
pub fn index(&self) -> usize {
self.position().get()
}
pub fn get<const Q: usize>(&self) -> Option<T> {
self.linked::<Q>(self.position())
.then(|| unsafe { (*self.value::<Q>()).assume_init_read() })
}
pub fn push<const Q: usize>(&self, value: T) {
let index = self.position();
if self.linked::<Q>(index) {
unsafe { self.write_back::<Q, true>(index, value) };
} else {
unsafe { self.write_back::<Q, false>(index, value) };
}
}
pub fn clear<const Q: usize>(&self) {
let index = self.position();
if self.linked::<Q>(index) {
unsafe { self.unlink::<Q>(index) };
}
}
}
const _: () = {
assert!(mem::size_of::<Fifo<u64>>() == 24);
assert!(mem::size_of::<Fifo<u64, (), 2>>() == 32);
assert!(mem::size_of::<Slot<'_, u64>>() == 16);
assert!(mem::size_of::<Option<Slot<'_, u64>>>() == 16);
assert!(mem::size_of::<Slot<'_, u64, (), 2>>() == 16);
assert!(mem::size_of::<Option<Slot<'_, u64, (), 2>>>() == 16);
};