use std::{marker, mem::ManuallyDrop, num, ptr};
use crate::{
alloc,
buffer::{
pool::{
self,
owners::{Edge, Header, Key, Plain, Resident, Shape, sealed},
state,
},
resident, storage,
},
mem::rc,
};
pub(in crate::buffer::pool) struct Block<K: crate::buffer::raw::Backing, S> {
base: ptr::NonNull<Header<K>>,
tail: ptr::NonNull<Slot<K>>,
state: marker::PhantomData<S>,
}
impl<K: crate::buffer::raw::Backing + Default, S: state::State> Block<K, S> {
pub(super) fn allocate(shape: Shape<K>) -> Result<Self, alloc::Exhausted> {
let base = unsafe { alloc::raw::try_new::<Header<K>>(shape.allocation(), S::ZEROED) }?;
let slots = shape.slots();
let mut tail = unsafe {
base.write(Header::new(shape));
base.add(1).cast::<Slot<K>>()
};
for index in 0..slots {
unsafe {
tail.write(Slot {
prefix: storage::raw::Prefix::empty(sealed::link(index + 1, slots)),
backing: K::default(),
});
tail = tail.add(1);
}
}
Ok(Self {
base,
tail,
state: marker::PhantomData,
})
}
}
impl<L: Into<pool::Layout>, S: state::State> Block<Plain<L>, S>
where
Plain<L>: crate::buffer::raw::Backing,
{
pub(in crate::buffer::pool) fn try_new(
layout: L,
) -> Result<Ptr<Plain<L>, S>, alloc::Exhausted> {
let block = Self::allocate(Shape::new(layout))?;
Ok(Ptr {
raw: block.base,
state: marker::PhantomData,
})
}
}
impl<S: state::State> Block<Plain<pool::Layout>, S> {
pub(in crate::buffer::pool) fn try_seed(
layout: pool::NonEmpty,
) -> Result<Seed<Plain<pool::Layout>, S>, alloc::Exhausted> {
Ok(Seed(Self::try_new(layout.into_layout())?))
}
}
impl<'d, S: state::State> Block<Resident<'d>, S> {
pub(in crate::buffer::pool) fn try_seed(
layout: pool::NonEmpty,
budget: resident::Budget<'d>,
) -> Result<Seed<Resident<'d>, S>, resident::AllocError> {
Ok(Seed(Self::try_new(layout.into(), budget)?))
}
pub(in crate::buffer::pool) fn try_new(
tally: pool::Tally,
budget: resident::Budget<'d>,
) -> Result<Ptr<Resident<'d>, S>, resident::AllocError> {
let shape = Shape::<Resident<'d>>::try_new(tally).map_err(resident::AllocError::Layout)?;
let (layout, limit) = tally.into_parts();
let charge = budget
.try_charge(layout.bytes())
.map_err(resident::AllocError::Budget)?;
let block = Self::allocate(shape).map_err(resident::AllocError::Exhausted)?;
Ok(unsafe { block.account(charge, limit) })
}
pub(super) unsafe fn account(
self,
charge: resident::Charge<'d>,
limit: u32,
) -> Ptr<Resident<'d>, S> {
unsafe {
self.tail
.cast::<super::Accounts<'d>>()
.write(super::Accounts::new(charge, limit))
};
Ptr {
raw: self.base,
state: marker::PhantomData,
}
}
}
#[repr(transparent)]
pub(in crate::buffer::pool) struct Seed<K, S>(Ptr<K, S>);
impl<K: crate::buffer::raw::Backing, S> Seed<K, S> {
pub(super) unsafe fn from_ptr(core: Ptr<K, S>) -> Self {
Self(core)
}
pub(in crate::buffer::pool) fn take(self) -> pool::Span<K, pool::Owned, S> {
unsafe { self.0.take(Key::FIRST, self.0.header().balance.get() - 1) }
}
pub(in crate::buffer::pool) fn into_span(self) -> pool::Span<K, pool::Owned, S> {
unsafe { self.0.take(Key::FIRST, -1) }
}
}
#[repr(transparent)]
#[derive(Debug)]
pub struct Ptr<K, S = state::Uninit> {
raw: ptr::NonNull<Header<K>>,
state: marker::PhantomData<(K, S)>,
}
impl<K, S> Clone for Ptr<K, S> {
fn clone(&self) -> Self {
*self
}
}
impl<K, S> Copy for Ptr<K, S> {}
impl<K, S> Ptr<K, S> {
pub(super) fn header(&self) -> &Header<K> {
unsafe { self.raw.as_ref() }
}
pub(in crate::buffer::pool) fn available(self) -> usize {
self.header().balance.get() as usize
}
pub(in crate::buffer::pool) const fn erase_state(self) -> Ptr<K, pool::Frozen> {
Ptr {
raw: self.raw,
state: marker::PhantomData,
}
}
}
impl<'d, S> Ptr<Resident<'d>, S> {
pub(super) fn accounts(self) -> ptr::NonNull<super::Accounts<'d>> {
unsafe {
self.raw
.add(1)
.cast::<Slot<Resident<'d>>>()
.add(self.header().slots() as usize)
.cast()
}
}
}
impl<K: crate::buffer::raw::Backing, S> Ptr<K, S> {
pub(in crate::buffer::pool) fn acquire(self) -> Option<pool::Span<K, pool::Owned, S>> {
let key = self.header().free.head()?;
Some(unsafe { self.take(key, self.header().balance.get() - 1) })
}
unsafe fn take(self, key: Key, balance: i64) -> pool::Span<K, pool::Owned, S> {
use crate::mem::raw::Edge;
let slot = self.slot(key);
let header = self.header();
unsafe {
key.occupy(&header.free, &slot.prefix);
if K::COUNTED {
slot.activate();
}
}
header.balance.set(balance);
pool::Span {
slots: self,
key,
len: 0,
root: pool::Owned,
}
}
pub(in crate::buffer::pool) fn data(self, key: Key) -> *mut u8 {
let offset = self.data_offset().get() + key.get() as usize * self.capacity().get() as usize;
unsafe { self.raw.as_ptr().cast::<u8>().add(offset) }
}
pub(in crate::buffer) unsafe fn deallocate(self) {
let layout = Shape::from_ptr(self).allocation();
unsafe { alloc::raw::dealloc(layout, self.raw) };
}
pub(in crate::buffer::pool) fn capacity(self) -> num::NonZero<u32> {
match K::CAPACITY {
Some(capacity) => capacity,
None => self.header().capacity(),
}
}
pub(in crate::buffer::pool) fn slots(self) -> usize {
match K::SLOTS {
Some(slots) => slots as usize,
None => self.header().slots() as usize,
}
}
pub(super) fn data_offset(self) -> num::NonZero<usize> {
match K::SLOTS {
Some(slots) => pool::Layout::offset(slots),
None => self.header().data_offset(),
}
}
pub(in crate::buffer::pool) fn ptr(self, key: Key) -> ptr::NonNull<Slot<K>> {
unsafe { self.raw.add(1).cast::<Slot<K>>().add(key.get() as usize) }
}
pub(in crate::buffer::pool) fn slot(&self, key: Key) -> &Slot<K> {
unsafe { self.ptr(key).as_ref() }
}
pub(in crate::buffer::pool) fn release_root(self) {
let balance = self.header().balance.get() - self.slots() as i64;
unsafe { self.retire(balance) };
}
unsafe fn retire(self, balance: i64) {
if balance == 0 {
unsafe { K::release(self) };
} else {
self.header().balance.set(balance);
}
}
}
#[derive(Debug)]
#[repr(C, align(8))]
pub(in crate::buffer) struct Slot<K: crate::buffer::raw::Backing = Plain> {
pub(super) prefix: storage::raw::Prefix,
pub(super) backing: K,
}
impl<K: crate::buffer::raw::Backing> Slot<K> {
pub(super) unsafe fn locate(pointer: ptr::NonNull<Self>) -> (Ptr<K, ()>, Key) {
let key = unsafe { Key::new(pointer.as_ref().prefix.word()) };
let offset = size_of::<Header<K>>() + key.get() as usize * size_of::<Self>();
let raw = unsafe { pointer.cast::<u8>().sub(offset).cast() };
(
Ptr {
raw,
state: marker::PhantomData,
},
key,
)
}
pub(in crate::buffer) unsafe fn capacity(pointer: ptr::NonNull<Self>) -> num::NonZero<u32> {
unsafe { Self::locate(pointer) }.0.capacity()
}
pub(in crate::buffer::pool) unsafe fn release<S>(
slot: ptr::NonNull<Self>,
core: Ptr<K, S>,
key: Key,
) {
use crate::mem::raw::Edge;
if K::COUNTED && unsafe { slot.as_ref().release() } != rc::Release::Last {
return;
}
unsafe { Self::recycle(slot, core, key) };
}
unsafe fn recycle<S>(slot: ptr::NonNull<Self>, core: Ptr<K, S>, key: Key) {
let header = core.header();
let balance = header.balance.get() + 1;
if balance > 0 {
unsafe { key.recycle(&header.free, &slot.as_ref().prefix) };
}
unsafe { core.retire(balance) };
}
}
unsafe impl<K: crate::buffer::raw::Backing> crate::mem::raw::Edge for Slot<K> {
fn count(&self) -> &crate::mem::raw::Count {
crate::mem::raw::Edge::count(&self.prefix)
}
}
unsafe impl<K: crate::buffer::raw::Backing> crate::mem::raw::Target for Slot<K> {
unsafe fn destroy(slot: ptr::NonNull<Self>) {
unsafe {
let (core, key) = Self::locate(slot);
Self::recycle(slot, core, key);
}
}
}
unsafe impl<K: crate::buffer::raw::Backing, M> crate::buffer::raw::Retain for Edge<K, M> {
fn try_retain(&self) -> Result<Self, rc::Error> {
Ok(Self {
slot: self.slot.try_clone()?,
mode: marker::PhantomData,
})
}
}
impl<K: crate::buffer::raw::Backing> Slot<K> {
pub(super) fn resident<M>(edge: &Edge<K, M>) -> usize {
unsafe { Self::capacity(edge.slot.as_ptr()) }.get() as usize
}
pub(super) fn share<M, S>(span: pool::Span<K, M, S>) -> Edge<K, M> {
use crate::mem::raw::Edge as _;
let span = ManuallyDrop::new(span);
let slot = span.slots.ptr(span.key);
unsafe {
if !K::COUNTED {
slot.as_ref().activate();
}
Edge {
slot: crate::mem::raw::Owner::from_raw(slot),
mode: marker::PhantomData,
}
}
}
}
const _: () = {
assert!(size_of::<Plain>() == 0);
assert!(size_of::<Resident<'_>>() == size_of::<u32>());
assert!(size_of::<Option<Edge>>() == size_of::<usize>());
assert!(size_of::<Option<Edge<Plain, pool::Borrowed<'_>>>>() == size_of::<usize>());
assert!(size_of::<Option<Edge<Resident<'_>>>>() == size_of::<usize>());
assert!(size_of::<Slot>() == 8);
assert!(size_of::<Slot<Resident<'static>>>() == 16);
assert!(align_of::<Slot>() == 8);
assert!(size_of::<Seed<Plain, state::Uninit>>() == size_of::<usize>());
assert!(size_of::<(Ptr<Plain, ()>, Key)>() == 2 * size_of::<usize>());
assert!(size_of::<(Ptr<Resident<'_>, ()>, Key)>() == 2 * size_of::<usize>());
assert!(size_of::<Block<Plain<pool::Fixed<1, 1>>, state::Uninit>>() == 2 * size_of::<usize>());
assert!(size_of::<Block<Plain<pool::Layout>, state::Uninit>>() == 2 * size_of::<usize>());
assert!(size_of::<Block<Plain<pool::Width<1>>, state::Uninit>>() == 2 * size_of::<usize>());
assert!(size_of::<Block<Resident<'_>, state::Uninit>>() == 2 * size_of::<usize>());
assert!(size_of::<Ptr<Plain>>() == size_of::<usize>());
assert!(size_of::<Ptr<Resident<'static>>>() == size_of::<usize>());
};