use std::{marker, num};
use o3::{alloc::tail, depot::arena::linked::chain};
use crate::driver::{
receive::credit::{sealed::groups, storage, storage::error},
route::indices,
};
type Block<'a, C, E> = tail::raw::View<'a, chain::Node<storage::Group<C>, E>, E>;
#[must_use = "dropping slots retires their group"]
pub struct Slots<'owner, T: Copy, S: Copy, C> {
pub(in crate::driver::receive::credit) block: Block<'owner, C, storage::Entry<T, S, C>>,
pub(in crate::driver::receive::credit) capacity: num::NonZero<u32>,
}
impl<'owner, T: Copy, S: Copy, C> Slots<'owner, T, S, C> {
pub fn get(
&self,
index: indices::SlotIndex,
) -> Result<storage::Slot<'_, 'owner, T, S, C>, error::Index> {
Ok(storage::Slot {
entry: groups::entries(self)
.get(index.raw() as usize)
.ok_or(error::Index {
requested: index,
capacity: self.capacity,
})?,
active: marker::PhantomData,
})
}
pub fn iter(&self) -> impl Iterator<Item = storage::Slot<'_, 'owner, T, S, C>> {
groups::entries(self).iter().map(|entry| storage::Slot {
entry,
active: marker::PhantomData,
})
}
}
impl<T: Copy, S: Copy, C> Drop for Slots<'_, T, S, C> {
fn drop(&mut self) {
let owners = self.iter().filter(|slot| slot.is_held()).count();
let group = &self.block.header().value;
group.attachment.set(storage::Attachment::Retired);
group.retire(owners);
}
}