use std::{cell, mem, num};
use credit::fair;
pub use lanes::Lanes;
use crate::{
base::cell::region,
depot::{capacity, queue::pool},
mem::{credit, raw::Balance},
};
mod lanes;
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Plan {
slots: capacity::Count,
lanes: num::NonZero<u32>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Error {
ZeroLanes { capacity: usize },
CapacityBelowLanes { capacity: usize, lanes: usize },
Capacity(capacity::Error),
}
const _: () = assert!(std::mem::size_of::<Plan>() == 2 * std::mem::size_of::<u32>());
impl Plan {
#[inline]
pub fn new(capacity: usize, lanes: usize) -> Result<Self, Error> {
if capacity < lanes {
return Err(Error::CapacityBelowLanes { capacity, lanes });
}
let lanes = num::NonZero::new(lanes).ok_or(Error::ZeroLanes { capacity })?;
let slots = capacity::Count::try_from(capacity).map_err(Error::Capacity)?;
Ok(Self {
slots,
lanes: capacity::Count::try_nonzero(lanes).map_err(Error::Capacity)?,
})
}
}
pub struct State<S> {
value: S,
held: cell::Cell<capacity::Count>,
index: capacity::Count,
}
impl<S> State<S> {
pub const fn value(&self) -> &S {
&self.value
}
}
pub struct Binding<'a, 'd, T, S = ()> {
owner: &'a Lanes<'d, T, S>,
slot: &'a cell::UnsafeCell<crate::depot::raw::QueueSlot<State<S>>>,
}
impl<'a, 'd, T, S> Binding<'a, 'd, T, S> {
pub fn from_source(
source: crate::depot::raw::Proof<(&'a Lanes<'d, T, S>, usize), capacity::Physical>,
) -> Self {
let (owner, index) = source.into_inner();
let slot = unsafe { &*owner.inner.slots.as_ptr().add(index).cast() };
Self { owner, slot }
}
pub const fn index(self) -> usize {
unsafe { (*self.slot.get()).state.index.get() }
}
pub fn view<'t>(
self,
_: &'t region::Token<region::Identity<'d>>,
) -> pool::View<'t, T, State<S>, false>
where
'a: 't,
{
unsafe { pool::View::new(&self.owner.inner.store, &*self.slot.get()) }
}
fn lane_mut<'t>(
self,
_: &'t mut region::Token<region::Identity<'d>>,
) -> pool::Lane<'t, T, State<S>, false>
where
'a: 't,
{
unsafe { pool::Lane::new(&self.owner.inner.store, &mut *self.slot.get()) }
}
fn held(self) -> &'a cell::Cell<capacity::Count> {
unsafe { &(*self.slot.get()).state.held }
}
fn balance(self) -> Balance<1, usize> {
Balance::new(
[self.held().get().get()],
[self.owner.inner.store.available()],
)
}
fn set_balance(self, balance: Balance<1, usize>) {
let ([held], [shared]) = balance.into_parts();
self.held().set(capacity::Count::new(held as u32));
self.owner.inner.store.available.set(shared as u32);
}
pub fn reserve(self) -> Result<Permit<'a, 'd, T, S>, fair::Cause<usize>> {
self.set_balance(self.balance().try_acquire([1], [1])?);
Ok(Permit { binding: self })
}
pub fn take_front(
self,
token: &mut region::Token<region::Identity<'d>>,
) -> Option<(T, Permit<'a, 'd, T, S>)> {
self.front_entry(token).map(|take| take())
}
pub fn front_entry<'t>(
self,
token: &'t mut region::Token<region::Identity<'d>>,
) -> Option<impl FnOnce() -> (T, Permit<'a, 'd, T, S>) + 't>
where
'a: 't,
{
let index = self.lane_mut(token).slot.queue.links.head()?;
Some(move || {
let lane = self.lane_mut(token);
let value = unsafe { lane.slot.queue.pop::<_, false>(lane.store, index) };
(value, Permit { binding: self })
})
}
}
impl<T, S> Copy for Binding<'_, '_, T, S> {}
impl<T, S> Clone for Binding<'_, '_, T, S> {
fn clone(&self) -> Self {
*self
}
}
#[must_use = "a fair queue reservation must be published or returned"]
pub struct Permit<'a, 'd, T, S = ()> {
binding: Binding<'a, 'd, T, S>,
}
impl<'a, 'd, T, S> Permit<'a, 'd, T, S> {
pub fn state_mut<'b>(
&'b self,
token: &'b mut region::Token<region::Identity<'d>>,
) -> &'b mut S {
&mut self.binding.lane_mut(token).into_state().value
}
pub fn push_back(self, token: &mut region::Token<region::Identity<'d>>, value: T) {
self.publish::<false>(token, value);
}
pub fn push_front(self, token: &mut region::Token<region::Identity<'d>>, value: T) {
self.publish::<true>(token, value);
}
fn publish<const FRONT: bool>(self, token: &mut region::Token<region::Identity<'d>>, value: T) {
let binding = mem::ManuallyDrop::new(self).binding;
unsafe { binding.lane_mut(token).insert_at::<FRONT>(value) };
}
}
impl<T, S> Drop for Permit<'_, '_, T, S> {
fn drop(&mut self) {
let binding = self.binding;
binding.set_balance(unsafe { binding.balance().release_raw([1], [1]) });
}
}
const _: () = {
const WORD: usize = mem::size_of::<usize>();
assert!(mem::size_of::<State<u64>>() == 2 * WORD);
assert!(mem::size_of::<Binding<'static, 'static, u64>>() == 2 * WORD);
assert!(mem::size_of::<Permit<'static, 'static, u64>>() == 2 * WORD);
assert!(mem::size_of::<Option<Permit<'static, 'static, u64>>>() == 2 * WORD);
};