use crate::slab_slice_arc::SlabSliceArc;
use core::{
ops::Deref,
sync::atomic::Ordering,
};
use core::marker::PhantomData;
use crate::byte_slab::BSlab;
pub struct SlabArc<const N: usize, const SZ: usize> {
pub(crate) slab: &'static BSlab<N, SZ>,
pub(crate) idx: usize,
}
pub struct RerooterKey<'a> {
pub(crate) start: *const u8,
pub(crate) end: *const u8,
pub(crate) pdlt: PhantomData<&'a ()>,
pub(crate) slab: *const (),
pub(crate) idx: usize,
}
impl<const N: usize, const SZ: usize> SlabArc<N, SZ> {
pub fn full_sub_slice_arc(&self) -> SlabSliceArc<N, SZ> {
SlabSliceArc {
arc: self.clone(),
start: 0,
len: self.len(),
}
}
pub fn rerooter_key<'a>(&'a self) -> RerooterKey<'a> {
let slice = self.deref();
RerooterKey {
start: slice.as_ptr(),
end: unsafe { slice.as_ptr().add(slice.len()) },
pdlt: PhantomData,
slab: (self.slab as *const BSlab<N, SZ>).cast(),
idx: self.idx,
}
}
pub fn sub_slice_arc(&self, start: usize, len: usize) -> Result<SlabSliceArc<N, SZ>, ()> {
let new_arc = self.clone();
let good_start = start < SZ;
let good_len = (start + len) <= SZ;
if good_start && good_len {
let new_slice_arc = SlabSliceArc {
arc: new_arc,
start,
len,
};
Ok(new_slice_arc)
} else {
Err(())
}
}
}
impl<const N: usize, const SZ: usize> Drop for SlabArc<N, SZ> {
fn drop(&mut self) {
let arc = unsafe { self.slab.get_idx_unchecked(self.idx).arc };
let refct = arc.fetch_sub(1, Ordering::SeqCst);
if refct == 1 {
if let Ok(q) = self.slab.get_q() {
while let Err(_) = q.enqueue(self.idx) {}
}
}
}
}
impl<const N: usize, const SZ: usize> Deref for SlabArc<N, SZ> {
type Target = [u8; SZ];
fn deref(&self) -> &Self::Target {
let buf = unsafe { self.slab.get_idx_unchecked(self.idx).buf };
unsafe { &*buf.get() }
}
}
impl<const N: usize, const SZ: usize> Clone for SlabArc<N, SZ> {
fn clone(&self) -> Self {
let arc = unsafe { self.slab.get_idx_unchecked(self.idx).arc };
let old_ct = arc.fetch_add(1, Ordering::SeqCst);
assert!(old_ct >= 1);
Self {
slab: self.slab,
idx: self.idx,
}
}
}