use core::num::NonZero;
use o3::depot::array;
pub(super) struct State<const N: usize> {
len: array::Len<N>,
next: array::Len<N>,
left: Option<NonZero<u32>>,
}
pub(super) struct Push<'a, const N: usize> {
state: &'a mut State<N>,
slot: array::Vacancy<N>,
}
pub(super) struct Fresh<'a, const N: usize> {
state: &'a mut State<N>,
slot: array::Vacancy<N>,
left: NonZero<u32>,
}
pub(super) struct Pending<'a, const N: usize> {
state: &'a mut State<N>,
left: NonZero<u32>,
}
pub(super) enum Completion {
Pending,
Ready,
}
pub(super) enum Status<const N: usize> {
Live,
Done(array::Len<N>),
}
pub(super) enum PendingState<'a, const N: usize> {
Live(Pending<'a, N>),
Done(array::Len<N>),
}
impl<const N: usize> State<N> {
pub(super) fn new(len: array::Len<N>) -> Self {
Self {
len,
next: array::Len::ZERO,
left: NonZero::<u32>::new(len.get() as u32),
}
}
pub(super) const fn next(&self) -> array::Len<N> {
self.next
}
pub(super) const fn completed(&self) -> Option<array::Len<N>> {
if self.left.is_some() {
return None;
}
Some(self.len)
}
pub(super) fn vacancy(&mut self) -> Option<Push<'_, N>> {
if !self.next.is_empty() {
return None;
}
let slot = self.len.vacancy()?;
Some(Push { state: self, slot })
}
pub(super) fn fresh(&mut self) -> Option<Fresh<'_, N>> {
let slot = self
.next
.vacancy()
.filter(|slot| slot.index() < self.len.get())?;
let left = self.left?;
Some(Fresh {
state: self,
slot,
left,
})
}
pub(super) fn pending(&mut self) -> PendingState<'_, N> {
let Some(left) = self.left else {
return PendingState::Done(self.len);
};
PendingState::Live(Pending { state: self, left })
}
}
impl<const N: usize> Push<'_, N> {
pub(super) const fn slot(&self) -> &array::Vacancy<N> {
&self.slot
}
pub(super) fn commit(self) {
let len = self.slot.commit();
self.state.len = len;
self.state.left = NonZero::new(len.get() as u32);
}
}
impl<const N: usize> Fresh<'_, N> {
pub(super) const fn slot(&self) -> &array::Vacancy<N> {
&self.slot
}
pub(super) fn commit(self, done: Completion) -> Status<N> {
self.state.next = self.slot.commit();
Pending {
state: self.state,
left: self.left,
}
.commit(done)
}
}
impl<const N: usize> Pending<'_, N> {
pub(super) fn commit(self, done: Completion) -> Status<N> {
if let Completion::Pending = done {
return Status::Live;
}
self.state.left = NonZero::<u32>::new(self.left.get() - 1);
match self.state.left {
Some(_) => Status::Live,
None => Status::Done(self.state.len),
}
}
}