use std::{array, mem, num::NonZero};
use slab::phase;
use crate::depot::{
arena::slab::key,
array::Index,
capacity,
queue::{indexed::slab, links, tagged},
};
const END: u32 = links::Index::END;
pub struct Reserved<
'a,
T,
Tag,
const MAX: u32,
H: crate::depot::raw::IndexedHook,
const N: usize,
const M: usize,
C: crate::depot::raw::Count,
> {
core: &'a mut slab::Slab<T, Tag, MAX, H, N, C>,
}
impl<
'a,
T,
Tag,
const MAX: u32,
H: crate::depot::raw::IndexedHook,
const N: usize,
const M: usize,
C: crate::depot::raw::Count,
> Reserved<'a, T, Tag, MAX, H, N, M, C>
{
pub(in crate::depot) fn admit(core: &'a mut slab::Slab<T, Tag, MAX, H, N, C>) -> Option<Self> {
(M <= core.available()).then(|| unsafe { Self::from_source(core) })
}
pub(in crate::depot) unsafe fn from_source(
core: &'a mut slab::Slab<T, Tag, MAX, H, N, C>,
) -> Self {
Self { core }
}
pub(in crate::depot) fn into_parts(
self,
) -> (&'a mut slab::Slab<T, Tag, MAX, H, N, C>, [links::Index; M]) {
let core = self.core;
let free = core.available();
let slots = array::from_fn(|_| {
let state = core.block.state();
let index = if state.free == END {
let index = state.initialized;
unsafe {
core.block.metadata.add(index as usize).as_ptr().write(
crate::depot::raw::IndexedMeta {
generation: key::Generation::MIN,
hook: H::new(links::Index::new_raw(index), None),
},
);
core.block.state_mut().initialized += 1;
}
index
} else {
let index = state.free;
let meta = unsafe { core.block.metadata.add(index as usize).as_mut() };
let next = unsafe { meta.hook.next() };
meta.hook = H::new(unsafe { links::Index::new_raw(index) }, None);
unsafe { core.block.state_mut() }.free = next;
index
};
unsafe { links::Index::new_raw(index) }
});
if M != 0 {
unsafe { core.block.state_mut() }.available = (free - M) as u32;
}
(core, slots)
}
}
impl<'a, T, Tag, const LANES: usize, const M: usize, const MAX: u32, C: crate::depot::raw::Count>
Reserved<'a, T, Tag, MAX, tagged::raw::Hook, LANES, M, C>
{
pub fn new(
source: &'a mut slab::Slab<T, Tag, MAX, tagged::raw::Hook, LANES, C>,
) -> Result<Self, capacity::Shortage> {
let free = source.available();
Self::admit(source).ok_or_else(|| capacity::Shortage {
requested: unsafe { NonZero::new_unchecked(M) },
available: free,
})
}
}
impl<'a, T, Tag, const LANES: usize, const MAX: u32, C: crate::depot::raw::Count>
Reserved<'a, T, Tag, MAX, tagged::raw::Hook, LANES, 1, C>
{
pub fn into_entry(
self,
lane: Index<LANES>,
) -> slab::raw::Vacant<'a, T, Tag, MAX, tagged::raw::Hook, LANES, C, phase::Target<LANES>> {
let (core, [index]) = self.into_parts();
slab::raw::Vacant {
core,
index,
phase: phase::Vacant,
}
.select(lane)
}
}
const _: () = {
assert!(
mem::size_of::<Reserved<'_, u64, (), { u32::MAX }, tagged::raw::Hook, 1, 3, capacity::Count>>(
) == mem::size_of::<usize>()
);
assert!(
mem::size_of::<
Option<Reserved<'_, u64, (), { u32::MAX }, tagged::raw::Hook, 1, 3, capacity::Count>>,
>() == mem::size_of::<usize>()
);
};