use std::{cell, marker, num, ptr};
use crate::driver::receive::credit::{
error,
storage::{Attachment, Lease, Slots, State},
};
pub(in crate::driver::receive::credit) struct Group<C> {
owners: cell::Cell<num::NonZero<usize>>,
pub(in crate::driver::receive::credit) generation: cell::Cell<num::NonZero<u64>>,
pub(in crate::driver::receive::credit) context: cell::Cell<ptr::NonNull<C>>,
pub(in crate::driver::receive::credit) available: cell::Cell<bool>,
pub(in crate::driver::receive::credit) attachment: cell::Cell<Attachment>,
}
impl<C> Group<C> {
pub(in crate::driver::receive::credit) fn context(&self) -> &C {
unsafe { self.context.get().as_ref() }
}
pub(in crate::driver::receive::credit) fn new(context: &C) -> Self {
Self {
owners: cell::Cell::new(num::NonZero::<usize>::MIN),
generation: cell::Cell::new(num::NonZero::<u64>::MIN),
context: cell::Cell::new(ptr::NonNull::from(context)),
available: cell::Cell::new(false),
attachment: cell::Cell::new(Attachment::Active),
}
}
pub(in crate::driver::receive::credit) fn generation(&self) -> error::Generation {
let epoch = self.generation.get();
match self.attachment.get() {
Attachment::Active => error::Generation::Active(epoch),
Attachment::Retired => error::Generation::Retired(epoch),
}
}
pub(in crate::driver::receive::credit) fn release(&self) {
self.retire(self.owners.get().get() - 1);
}
pub(in crate::driver::receive::credit) fn retire(&self, left: usize) {
if let Some(rest) = num::NonZero::new(left) {
self.owners.set(rest);
} else if let Some(next) = self.generation.get().checked_add(1) {
self.generation.set(next);
self.available.set(true);
}
}
}
const _: () = {
use std::mem;
assert!(mem::size_of::<Group<usize>>() == 4 * mem::size_of::<usize>());
};
pub(in crate::driver::receive::credit) struct Entry<T: Copy, S: Copy, C> {
header: ptr::NonNull<Group<C>>,
pub(in crate::driver::receive::credit) state: cell::Cell<State<S>>,
invariant: marker::PhantomData<cell::Cell<T>>,
}
impl<T: Copy, S: Copy, C> Entry<T, S, C> {
pub(in crate::driver::receive::credit) fn header(&self) -> &Group<C> {
unsafe { self.header.as_ref() }
}
pub(in crate::driver::receive::credit) fn new(header: &Group<C>) -> Self {
Self {
header: ptr::NonNull::from(header),
state: cell::Cell::new(State::Idle),
invariant: marker::PhantomData,
}
}
pub(in crate::driver::receive::credit) fn arm(
&self,
target: T,
) -> Result<Lease<'_, T, S, C>, error::Arm> {
match self.state.get() {
State::Idle => {}
State::Held | State::Ready(..) => return Err(error::Arm::Busy),
State::Detached | State::DetachedHeld => return Err(error::Arm::Detached),
}
self.state.set(State::Held);
Ok(Lease {
entry: self,
target,
})
}
}
pub(in crate::driver::receive::credit) fn entries<'a, T: Copy, S: Copy, C>(
slots: &Slots<'a, T, S, C>,
) -> &'a [Entry<T, S, C>] {
unsafe {
slots
.block
.as_slice()
.get_unchecked(..slots.capacity.get() as usize)
}
}