use std::cell::Cell;
use crate::{buffer::storage::regions, depot::queue::links};
pub(super) const END: u32 = links::Index::encode(None);
pub(super) const fn link(index: u32, limit: u32) -> u32 {
if index == limit { END } else { index }
}
#[repr(transparent)]
pub(super) struct Free<const ACCOUNT: bool = false>(Cell<u32>);
impl<const ACCOUNT: bool> Free<ACCOUNT> {
pub(super) const fn new(limit: u32) -> Self {
Self(Cell::new(link(0, limit)))
}
pub(super) fn head(&self) -> Option<Key<ACCOUNT>> {
unsafe { Key::decode(self.0.get()) }
}
}
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::buffer::pool) struct Key<const ACCOUNT: bool = false>(u32);
impl<const ACCOUNT: bool> Key<ACCOUNT> {
pub(super) const unsafe fn new(index: u32) -> Self {
Self(unsafe { links::Index::new_raw(index) }.raw())
}
pub(super) const fn get(self) -> u32 {
self.0
}
pub(super) const unsafe fn decode(word: u32) -> Option<Self> {
match links::Index::decode(word) {
Some(index) => Some(Self(index.raw())),
None => None,
}
}
pub(super) unsafe fn recycle(self, head: &Free<ACCOUNT>, prefix: ®ions::Prefix) {
unsafe { prefix.write(head.0.get()) };
head.0.set(self.0);
}
}
impl Key {
pub(super) unsafe fn occupy<const ACCOUNT: bool>(
self,
head: &Free<ACCOUNT>,
prefix: ®ions::Prefix,
) {
head.0.set(prefix.word());
unsafe { prefix.write(self.0) };
}
}
const _: () = {
assert!(size_of::<Key>() == size_of::<u32>());
assert!(size_of::<Key<true>>() == size_of::<u32>());
assert!(size_of::<Free>() == size_of::<u32>());
assert!(size_of::<Free<true>>() == size_of::<u32>());
};