use std::{
cell::{Cell, UnsafeCell},
mem::MaybeUninit,
num::NonZero,
};
use crate::depot::{self, arena::linked::fifo::ends, queue::ring::inline};
#[derive(Clone, Copy, Eq, PartialEq)]
pub(in crate::depot::queue::ring) struct Index<const N: usize>(NonZero<usize>);
struct Slot<T, const N: usize, P> {
value: UnsafeCell<T>,
payload: Cell<MaybeUninit<P>>,
next: Cell<Option<Index<N>>>,
}
pub(in crate::depot::queue::ring) struct Slots<T, const N: usize, P> {
entries: [Slot<T, N, P>; N],
free: ends::Cell<Option<Index<N>>>,
pub(in crate::depot::queue::ring) pending: ends::Cell<Option<Index<N>>>,
}
impl<T, const N: usize, P: Copy> Slots<T, N, P> {
pub(in crate::depot::queue::ring) fn new(values: [T; N]) -> Self {
let mut current = NonZero::<usize>::MIN;
let entries = values.map(|value| {
let next = if current.get() == N {
None
} else {
current = current.saturating_add(1);
Some(Index(current))
};
Slot {
value: UnsafeCell::new(value),
payload: Cell::new(MaybeUninit::uninit()),
next: Cell::new(next),
}
});
let (head, tail) = match NonZero::new(N) {
Some(last) => (Some(Index(NonZero::<usize>::MIN)), Some(Index(last))),
None => (None, None),
};
Self {
entries,
free: unsafe { ends::Cell::from_parts(head, tail) },
pending: ends::Cell::empty(),
}
}
fn slot(&self, index: Index<N>) -> &Slot<T, N, P> {
unsafe { self.entries.get_unchecked(index.0.get() - 1) }
}
fn pop(&self, list: &ends::Cell<Option<Index<N>>>) -> Option<Index<N>> {
let index = list.head()?;
let next = self.slot(index).next.get();
unsafe { depot::raw::EndsPop::advance(list, next) };
Some(index)
}
pub(in crate::depot::queue::ring) fn acquire(&self) -> Option<Index<N>> {
self.pop(&self.free)
}
pub(in crate::depot::queue::ring) fn take(&self) -> Option<(Index<N>, P)> {
let index = self.pop(&self.pending)?;
Some((index, unsafe {
self.slot(index).payload.get().assume_init()
}))
}
pub(in crate::depot::queue::ring) fn value<'a>(lease: &'a inline::Lease<'_, T, N, P>) -> &'a T {
let slot = lease.pool.slots.slot(lease.index);
unsafe { &*slot.value.get() }
}
pub(in crate::depot::queue::ring) fn value_mut<'a>(
lease: &'a mut inline::Lease<'_, T, N, P>,
) -> &'a mut T {
let slot = lease.pool.slots.slot(lease.index);
unsafe { &mut *slot.value.get() }
}
pub(in crate::depot::queue::ring) fn publish(lease: inline::Lease<'_, T, N, P>, payload: P) {
let slots = &lease.pool.slots;
let slot = slots.slot(lease.index);
slot.payload.set(MaybeUninit::new(payload));
slots.link(lease.index, slot, &slots.pending);
}
pub(in crate::depot::queue::ring) fn release(lease: inline::Lease<'_, T, N, P>) {
let slots = &lease.pool.slots;
slots.link(lease.index, slots.slot(lease.index), &slots.free);
}
fn link(&self, index: Index<N>, slot: &Slot<T, N, P>, list: &ends::Cell<Option<Index<N>>>) {
slot.next.set(None);
let tail = list.back();
if let Some(tail) = tail {
self.slot(tail).next.set(Some(index));
}
ends::Cell::push_back(unsafe { depot::raw::Proof::new((list, index, tail)) });
}
}